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

// GET /api/routing - Get quote routing history
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 quoteId = searchParams.get('quoteId');

    const where: any = {};
    if (quoteId) {
      where.quoteId = quoteId;
    }

    const routings = await prisma.quoteRouting.findMany({
      where,
      orderBy: { routedAt: 'desc' },
    });

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

// POST /api/routing - Route or reroute quote
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, contractorId, attemptNumber } = body;

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

    const routing = await prisma.quoteRouting.create({
      data: {
        quoteId,
        contractorId,
        attemptNumber: attemptNumber || 1,
        status: 'PENDING',
      },
    });

    return NextResponse.json({ routing, message: 'Quote routed successfully' }, { status: 201 });
  } catch (error) {
    console.error('Error routing quote:', error);
    return NextResponse.json(
      { error: 'Failed to route quote' },
      { status: 500 }
    );
  }
}
