export const dynamic = 'force-dynamic';

import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/db';
import { resolveSniffCheck, getPendingSniffChecks, getSniffCheckStats } from '@/lib/order-to-cash/sniff-check';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const action = searchParams.get('action');

    if (action === 'stats') {
      const stats = await getSniffCheckStats();
      return NextResponse.json(stats);
    }

    const limit = parseInt(searchParams.get('limit') || '50');
    const pending = await getPendingSniffChecks(limit);
    
    return NextResponse.json({ sniffChecks: pending });
  } catch (error) {
    console.error('Error fetching sniff checks:', error);
    return NextResponse.json({ error: 'Failed to fetch sniff checks' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const { gateId, decision, reviewedBy, notes } = await request.json();

    if (!gateId || !decision || !reviewedBy) {
      return NextResponse.json(
        { error: 'Gate ID, decision, and reviewer required' },
        { status: 400 }
      );
    }

    if (decision !== 'approved' && decision !== 'rejected') {
      return NextResponse.json(
        { error: 'Decision must be approved or rejected' },
        { status: 400 }
      );
    }

    await resolveSniffCheck(gateId, reviewedBy, decision, notes);

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Error resolving sniff check:', error);
    return NextResponse.json({ error: 'Failed to resolve sniff check' }, { status: 500 });
  }
}
