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

// PUT - Update an existing bid
export async function PUT(
  req: NextRequest,
  { params }: { params: { projectId: string; bidId: string } }
) {
  try {
    const session = await getServerSession(authOptions);
    
    if (!session?.user?.email) {
      return NextResponse.json(
        {
          success: false,
          error: 'Authentication Required',
          message: 'Please log in to update your bid. Your session may have expired.',
          action: 'redirect_login'
        },
        { status: 401 }
      );
    }

    // Check if the user is a freelancer
    if (session.user.role !== 'FREELANCER') {
      return NextResponse.json(
        {
          success: false,
          error: 'Forbidden',
          message: 'Only freelancers can update bids on projects.'
        },
        { status: 403 }
      );
    }

    const { projectId, bidId } = params;
    const body = await req.json();
    const { amount, deliveryTime, proposal } = body;

    // Validate required fields
    if (!amount || !deliveryTime || !proposal) {
      return NextResponse.json(
        { 
          success: false,
          error: 'Validation Failed',
          message: 'Please fill in all required fields: amount, delivery time, and proposal.',
          details: 'Missing required fields for bid update'
        },
        { status: 400 }
      );
    }

    // Check if bid exists and belongs to the user
    const existingBid = await prisma.bid.findFirst({
      where: {
        id: bidId,
        projectId,
        freelancerId: session.user.id
      },
      include: {
        project: {
          select: {
            id: true,
            title: true,
            status: true,
            clientId: true
          }
        }
      }
    });

    if (!existingBid) {
      return NextResponse.json(
        { 
          success: false,
          error: 'Bid Not Found',
          message: 'The bid you are trying to update does not exist or does not belong to you.',
          details: 'Bid not found or access denied'
        },
        { status: 404 }
      );
    }

    // Check if project is still open
    if (existingBid.project.status !== 'OPEN') {
      return NextResponse.json(
        { 
          success: false,
          error: 'Project Closed',
          message: 'This project is no longer accepting bid updates. It may have been awarded or cancelled.',
          details: `Project status is ${existingBid.project.status}`
        },
        { status: 400 }
      );
    }

    // Check if bid is still pending (can't update accepted/rejected bids)
    if (existingBid.status !== 'PENDING') {
      return NextResponse.json(
        { 
          success: false,
          error: 'Bid Cannot Be Updated',
          message: `Your bid has already been ${existingBid.status.toLowerCase()} and cannot be modified.`,
          details: `Bid status is ${existingBid.status}`
        },
        { status: 400 }
      );
    }

    // Update the bid
    const updatedBid = await prisma.bid.update({
      where: { id: bidId },
      data: {
        amount: parseFloat(amount),
        duration: parseInt(deliveryTime),
        proposal,
        updatedAt: new Date()
      },
      include: {
        project: {
          select: {
            title: true,
            client: {
              select: {
                id: true,
                email: true,
                profile: {
                  select: {
                    firstName: true,
                    lastName: true
                  }
                }
              }
            }
          }
        }
      }
    });

    // TODO: Send notification to project owner about bid update

    return NextResponse.json({
      success: true,
      message: `Bid updated successfully! Your updated proposal of €${updatedBid.amount} with ${updatedBid.duration} days delivery has been sent to the client.`,
      data: {
        bid: {
          id: updatedBid.id,
          amount: updatedBid.amount,
          deliveryTime: updatedBid.duration,
          proposal: updatedBid.proposal,
          status: updatedBid.status,
          updatedAt: updatedBid.updatedAt.toISOString()
        },
        projectTitle: updatedBid.project?.title || 'Unknown Project'
      }
    });

  } catch (error) {
    console.error('Error updating bid:', error);
    
    let errorMessage = 'Unable to update your bid at this time. Please try again later.';
    let details = 'Unknown error occurred';
    
    if (error instanceof Error) {
      details = error.message;
      
      if (error.message.includes('connect') || error.message.includes('ECONNREFUSED')) {
        errorMessage = 'Database connection failed. Please contact support if this persists.';
      } else if (error.message.includes('constraint') || error.message.includes('duplicate')) {
        errorMessage = 'Invalid bid data provided.';
      } else if (error.message.includes('validation') || error.message.includes('invalid')) {
        errorMessage = 'Invalid bid data provided. Please check your inputs.';
      }
    }
    
    return NextResponse.json(
      { 
        success: false,
        error: 'Bid Update Failed',
        message: errorMessage,
        details: details,
        support: 'If this error persists, please contact support with error code: BID_UPDATE_001'
      },
      { status: 500 }
    );
  }
}

// DELETE - Withdraw a bid
export async function DELETE(
  req: NextRequest,
  { params }: { params: { projectId: string; bidId: string } }
) {
  try {
    const session = await getServerSession(authOptions);
    
    if (!session?.user?.email) {
      return NextResponse.json(
        {
          success: false,
          error: 'Authentication Required',
          message: 'Please log in to withdraw your bid. Your session may have expired.',
          action: 'redirect_login'
        },
        { status: 401 }
      );
    }

    // Check if the user is a freelancer
    if (session.user.role !== 'FREELANCER') {
      return NextResponse.json(
        {
          success: false,
          error: 'Forbidden',
          message: 'Only freelancers can withdraw bids on projects.'
        },
        { status: 403 }
      );
    }

    const { projectId, bidId } = params;

    // Check if bid exists and belongs to the user
    const existingBid = await prisma.bid.findFirst({
      where: {
        id: bidId,
        projectId,
        freelancerId: session.user.id
      },
      include: {
        project: {
          select: {
            id: true,
            title: true,
            status: true,
            clientId: true
          }
        }
      }
    });

    if (!existingBid) {
      return NextResponse.json(
        { 
          success: false,
          error: 'Bid Not Found',
          message: 'The bid you are trying to withdraw does not exist or does not belong to you.',
          details: 'Bid not found or access denied'
        },
        { status: 404 }
      );
    }

    // Check if bid can be withdrawn (only pending bids)
    if (existingBid.status !== 'PENDING') {
      return NextResponse.json(
        { 
          success: false,
          error: 'Bid Cannot Be Withdrawn',
          message: `Your bid has already been ${existingBid.status.toLowerCase()} and cannot be withdrawn.`,
          details: `Bid status is ${existingBid.status}`
        },
        { status: 400 }
      );
    }

    // Delete the bid
    await prisma.bid.delete({
      where: { id: bidId }
    });

    // TODO: Send notification to project owner about bid withdrawal

    return NextResponse.json({
      success: true,
      message: 'Bid withdrawn successfully. The client will no longer see your proposal for this project.',
      data: {
        bidId: bidId,
        projectId: projectId,
        projectTitle: existingBid.project?.title || 'Unknown Project'
      }
    });

  } catch (error) {
    console.error('Error withdrawing bid:', error);
    
    let errorMessage = 'Unable to withdraw your bid at this time. Please try again later.';
    let details = 'Unknown error occurred';
    
    if (error instanceof Error) {
      details = error.message;
      
      if (error.message.includes('connect') || error.message.includes('ECONNREFUSED')) {
        errorMessage = 'Database connection failed. Please contact support if this persists.';
      } else if (error.message.includes('constraint')) {
        errorMessage = 'Cannot withdraw bid due to existing constraints.';
      }
    }
    
    return NextResponse.json(
      { 
        success: false,
        error: 'Bid Withdrawal Failed',
        message: errorMessage,
        details: details,
        support: 'If this error persists, please contact support with error code: BID_WITHDRAW_001'
      },
      { status: 500 }
    );
  }
}