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

// POST /api/routing/escalate - Escalate quote routing
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 { routingId, reason } = body;

    if (!routingId) {
      return NextResponse.json(
        { error: 'Routing ID is required' },
        { status: 400 }
      );
    }

    const routing = await prisma.quoteRouting.update({
      where: { id: routingId },
      data: {
        escalated: true,
        escalatedAt: new Date(),
        status: 'ESCALATED',
        rejectionReason: reason,
      },
    });

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