
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;

    // 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 or expired
    if (quote.isAccepted) {
      return NextResponse.json(
        { error: 'Quote already accepted' },
        { status: 400 }
      );
    }

    if (new Date(quote.validUntil) < new Date()) {
      return NextResponse.json(
        { error: 'Quote has expired' },
        { status: 400 }
      );
    }

    // Update the quote
    const updatedQuote = await prisma.quote.update({
      where: { id: quoteId },
      data: {
        status: 'ACCEPTED',
        isAccepted: true,
        acceptedAt: new Date(),
      },
    });

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

    // Create a notification for the sales person
    await prisma.notification.create({
      data: {
        userId: quote.userId,
        title: 'Quote Accepted',
        message: `Customer has accepted quote ${quote.quoteNumber} for $${quote.total.toLocaleString()}`,
        type: 'QUOTE_APPROVED',
        metadata: {
          quoteId: quote.id,
          quoteNumber: quote.quoteNumber,
          amount: quote.total,
        },
      },
    });

    // Create audit log
    await prisma.auditLog.create({
      data: {
        userId: session.user.id,
        entityType: 'quote',
        entityId: quote.id,
        action: 'accept',
        oldData: { status: quote.status, isAccepted: quote.isAccepted },
        newData: { status: 'ACCEPTED', isAccepted: true },
        metadata: {
          quoteNumber: quote.quoteNumber,
          acceptedAt: new Date().toISOString(),
        },
      },
    });

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