import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';

export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    if (!prisma) {
      return NextResponse.json(
        { error: 'Database connection not available' },
        { status: 503 }
      );
    }

    const session = await getServerSession(authOptions);
    
    if (!session?.user?.email) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    const { projectId } = await params;

    if (!projectId) {
      return NextResponse.json(
        { error: 'Project ID is required' },
        { status: 400 }
      );
    }

    try {
      // TODO: Re-enable when all missing models and fields are available
      // const project = await prisma.project.findFirst({
      //   where: {
      //     id: projectId,
      //     status: 'CANCELLED',
      //     OR: [
      //       { clientId: session.user.email },
      //       {
      //         bids: {
      //           some: {
      //             freelancerId: session.user.email,
      //             status: 'ACCEPTED'
      //           }
      //         }
      //       }
      //     ]
      //   },
      //   include: {
      //     client: {
      //       select: {
      //         id: true,
      //         email: true,
      //         profile: {
      //           select: {
      //             firstName: true,
      //             lastName: true
      //           }
      //         }
      //       }
      //     },
      //     bids: {
      //       where: {
      //         status: 'ACCEPTED'
      //       },
      //       include: {
      //         freelancer: {
      //           select: {
      //             id: true,
      //             email: true,
      //             profile: {
      //               select: {
      //                 firstName: true,
      //                 lastName: true
      //               }
      //             }
      //           }
      //         }
      //       }
      //     },
      //     category: {
      //       select: {
      //         name: true
      //       }
      //     }
      //   }
      // });

      // Return mock cancelled project data
      const mockProject = {
        id: projectId,
        title: 'E-commerce Website Development',
        description: 'Develop a modern, responsive e-commerce website with payment integration, user authentication, and admin panel.',
        status: 'CANCELLED',
        budget: 2500,
        currency: 'USD', // Mock field
        deadline: '2024-08-15T00:00:00Z', // Mock field
        createdAt: '2024-06-01T09:00:00Z',
        cancelledAt: '2024-06-15T14:30:00Z',
        clientId: 'client-456',
        clientName: 'Sarah Johnson',
        clientEmail: 'sarah.johnson@example.com',
        clientAvatar: '/assets/image/profile02.png',
        freelancerId: 'freelancer-123',
        freelancerName: 'John Smith',
        freelancerEmail: 'john.smith@example.com',
        freelancerAvatar: '/assets/image/freelancer-avatar.png',
        category: 'Web Development',
        cancellation: {
          id: 'cancellation-1',
          reason: 'Client requirements changed significantly',
          cancelledBy: 'client',
          cancelledAt: '2024-06-15T14:30:00Z',
          refundAmount: 1875, // 75% refund
          refundStatus: 'pending'
        },
        userRole: session.user.email === 'client-456' ? 'client' : 'freelancer'
      };

      return NextResponse.json({
        success: true,
        data: mockProject
      });

    } catch (dbError) {
      console.error('Database query error:', dbError);
      
      // Return mock cancelled project when database is not ready
      const mockProject = {
        id: projectId,
        title: 'E-commerce Website Development',
        description: 'Develop a modern, responsive e-commerce website with payment integration, user authentication, and admin panel.',
        status: 'CANCELLED',
        budget: 2500,
        currency: 'USD',
        deadline: '2024-08-15T00:00:00Z',
        createdAt: '2024-06-01T09:00:00Z',
        cancelledAt: '2024-06-15T14:30:00Z',
        clientId: 'client-456',
        clientName: 'Sarah Johnson',
        clientEmail: 'sarah.johnson@example.com',
        clientAvatar: '/assets/image/profile02.png',
        freelancerId: 'freelancer-123',
        freelancerName: 'John Smith',
        freelancerEmail: 'john.smith@example.com',
        freelancerAvatar: '/assets/image/freelancer-avatar.png',
        category: 'Web Development',
        cancellation: {
          id: 'cancellation-1',
          reason: 'Client requirements changed significantly',
          cancelledBy: 'client',
          cancelledAt: '2024-06-15T14:30:00Z',
          refundAmount: 1875,
          refundStatus: 'pending'
        },
        userRole: 'client'
      };

      return NextResponse.json({
        success: true,
        data: mockProject
      });
    }

  } catch (error) {
    console.error('Error fetching cancelled project details:', error);
    
    return NextResponse.json(
      { 
        error: error instanceof Error ? error.message : 'Failed to fetch cancelled project details',
        type: 'server_error'
      },
      { status: 500 }
    );
  }
}