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

// GET /api/quote-rejections - Get quote rejections
export async function GET(req: NextRequest) {
  try {
    const session = await getServerSession();
    if (!session?.user?.email) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const { searchParams } = new URL(req.url);
    const recovered = searchParams.get('recovered');
    const reason = searchParams.get('reason');

    const where: any = {};
    if (recovered !== null) {
      where.recovered = recovered === 'true';
    }
    if (reason) {
      where.reason = reason;
    }

    const rejections = await prisma.quoteRejection.findMany({
      where,
      orderBy: { createdAt: 'desc' },
    });

    return NextResponse.json({ rejections });
  } catch (error) {
    console.error('Error fetching quote rejections:', error);
    return NextResponse.json(
      { error: 'Failed to fetch quote rejections' },
      { status: 500 }
    );
  }
}

// POST /api/quote-rejections - Record quote rejection
export async function POST(req: NextRequest) {
  try {
    const session = await getServerSession();
    if (!session?.user?.email) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await req.json();
    const {
      quoteId,
      customerId,
      reason,
      specificFeedback,
      priceIssue,
      timelineIssue,
      competitorPrice,
      competitorName,
    } = body;

    if (!quoteId || !customerId || !reason) {
      return NextResponse.json(
        { error: 'Quote ID, customer ID, and reason are required' },
        { status: 400 }
      );
    }

    const rejection = await prisma.quoteRejection.create({
      data: {
        quoteId,
        customerId,
        reason,
        specificFeedback,
        priceIssue: priceIssue || false,
        timelineIssue: timelineIssue || false,
        competitorPrice,
        competitorName,
      },
    });

    // Update quote status
    await prisma.quote.update({
      where: { id: quoteId },
      data: { status: 'REJECTED', rejectedAt: new Date(), rejectionReason: reason },
    });

    return NextResponse.json({ rejection }, { status: 201 });
  } catch (error) {
    console.error('Error recording quote rejection:', error);
    return NextResponse.json(
      { error: 'Failed to record quote rejection' },
      { status: 500 }
    );
  }
}
