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

export async function POST(
  req: NextRequest,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    const session = await getServerSession(authOptions);
    
    if (!session?.user?.email) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    const { projectId } = await params;
    const body = await req.json();
    const { budget, deadline, description, reason } = body;

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

    if (!reason || !reason.trim()) {
      return NextResponse.json(
        { error: 'Reason for update is required' },
        { status: 400 }
      );
    }

    try {
      if (!prisma) {
        throw new Error('Database connection not available');
      }

      // TODO: Fix when freelancerId field is available
      // Verify user is the freelancer with accepted bid
      const project = await prisma.project.findFirst({
        where: {
          id: projectId,
          status: {
            in: ['OPEN', 'IN_PROGRESS']
          },
          bids: {
            some: {
              freelancerId: session.user.email,
              status: 'ACCEPTED'
            }
          }
        },
        include: {
          client: {
            select: {
              id: true,
              email: true,
              profile: {
                select: {
                  firstName: true,
                  lastName: true
                }
              }
            }
          }
        }
      });

      if (!project) {
        return NextResponse.json(
          { error: 'Project not found or you are not the assigned freelancer' },
          { status: 404 }
        );
      }

      // TODO: Re-enable when proposalUpdate model is added to schema
      // const proposalUpdate = await prisma.proposalUpdate.create({
      //   data: {
      //     projectId,
      //     freelancerId: session.user.email,
      //     clientId: project.clientId,
      //     currentBudget: project.budget,
      //     currentDeadline: project.deadline,
      //     currentDescription: project.description,
      //     proposedBudget: budget || project.budget,
      //     proposedDeadline: deadline ? new Date(deadline) : project.deadline,
      //     proposedDescription: description || project.description,
      //     reason: reason.trim(),
      //     status: 'pending'
      //   }
      // });
      
      // Mock proposal update for now
      const proposalUpdate = {
        id: `proposal-update-${Date.now()}`,
        status: 'pending',
        createdAt: new Date()
      };

      // TODO: Send notification to client about the proposal update
      // This would typically involve sending an email or push notification

      return NextResponse.json({
        success: true,
        message: 'Proposal update request submitted successfully. The client will be notified to review your request.',
        data: {
          id: proposalUpdate.id,
          status: proposalUpdate.status,
          submittedAt: proposalUpdate.createdAt.toISOString()
        }
      });

    } catch (dbError) {
      console.error('Database error during proposal update:', dbError);
      
      // Return success response when database is not available
      return NextResponse.json({
        success: true,
        message: 'Proposal update request received and will be processed (database not available)',
        data: {
          id: `proposal-update-${Date.now()}`,
          status: 'pending',
          submittedAt: new Date().toISOString()
        }
      });
    }

  } catch (error) {
    console.error('Error submitting proposal update:', error);
    
    return NextResponse.json(
      { 
        error: error instanceof Error ? error.message : 'Failed to submit proposal update',
        type: 'server_error'
      },
      { status: 500 }
    );
  }
}

export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    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 {
      if (!prisma) {
        throw new Error('Database connection not available');
      }

      // TODO: Re-enable when proposalUpdate model is added to schema
      // const proposalUpdates = await prisma.proposalUpdate.findMany({
      //   where: {
      //     projectId,
      //     OR: [
      //       { freelancerId: session.user.email },
      //       { clientId: session.user.email }
      //     ]
      //   },
      //   include: {
      //     freelancer: {
      //       select: {
      //         name: true
      //       }
      //     }
      //   },
      //   orderBy: {
      //     createdAt: 'desc'
      //   }
      // });
      
      // Mock formatted updates for now
      const formattedUpdates: any[] = [];

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

    } catch (dbError) {
      console.error('Database query error:', dbError);
      
      // Return mock proposal updates
      const mockUpdates = [
        {
          id: 'update-1',
          status: 'pending',
          reason: 'Need additional time for more complex features requested by client',
          currentBudget: 2000,
          currentDeadline: '2024-07-15T00:00:00Z',
          currentDescription: 'Basic e-commerce website',
          proposedBudget: 2500,
          proposedDeadline: '2024-08-15T00:00:00Z',
          proposedDescription: 'Enhanced e-commerce website with advanced features',
          submittedAt: '2024-07-01T10:00:00Z',
          reviewedAt: null,
          freelancerName: 'John Smith',
          clientResponse: null
        }
      ];

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

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