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

export async function POST(
  request: NextRequest,
  { params }: { params: { quoteId: string } }
) {
  try {
    const session = await getServerSession(authOptions);

    if (!session?.user?.id) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    // Only customers can access this endpoint
    if (session.user.role !== 'CUSTOMER') {
      return NextResponse.json(
        { error: 'Forbidden - Customer access only' },
        { status: 403 }
      );
    }

    const { quoteId } = params;
    const body = await request.json();
    const { reason } = body;

    // Verify the quote belongs to the customer
    const quote = await prisma.quote.findFirst({
      where: {
        id: quoteId,
        userId: session.user.id,
      },
    });

    if (!quote) {
      return NextResponse.json(
        { error: 'Quote not found' },
        { status: 404 }
      );
    }

    // Check if quote is already accepted
    if (quote.isAccepted) {
      return NextResponse.json(
        { error: 'Cannot reject an accepted quote' },
        { status: 400 }
      );
    }

    // Update the quote
    const updatedQuote = await prisma.quote.update({
      where: { id: quoteId },
      data: {
        status: 'REJECTED',
        rejectedAt: new Date(),
        rejectionReason: reason || 'No reason provided',
      },
    });

    // Update the associated lead status
    await prisma.lead.update({
      where: { id: quote.leadId },
      data: {
        status: 'LOST',
      },
    });

    // Create a notification for the sales person
    await prisma.notification.create({
      data: {
        userId: quote.userId,
        title: 'Quote Rejected',
        message: `Customer has rejected quote ${quote.quoteNumber}`,
        type: 'QUOTE_REJECTED',
        metadata: {
          quoteId: quote.id,
          quoteNumber: quote.quoteNumber,
          reason: reason || 'No reason provided',
        },
      },
    });

    // Create audit log
    await prisma.auditLog.create({
      data: {
        userId: session.user.id,
        entityType: 'quote',
        entityId: quote.id,
        action: 'reject',
        oldData: { status: quote.status },
        newData: { status: 'REJECTED', rejectionReason: reason },
        metadata: {
          quoteNumber: quote.quoteNumber,
          rejectedAt: new Date().toISOString(),
        },
      },
    });

    return NextResponse.json({
      success: true,
      quote: updatedQuote,
    });
  } catch (error) {
    console.error('Error rejecting quote:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}
