import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';

export async function GET(
  request: Request,
  props: { params: Promise<{ id: string }> | { id: string } }
) {
  try {
    const resolvedParams = await Promise.resolve(props?.params || {});
    const id = resolvedParams.id;
    if (!id) {
      return NextResponse.json({ error: 'ID is required' }, { status: 400 });
    }

    const rejection = await prisma.qcRejection.findFirst({
      where: {
        OR: [
          { id },
          { orderLineId: id }
        ]
      },
      include: {
        farm: { select: { id: true, name: true, ruc: true } }
      }
    });

    if (!rejection) {
      return NextResponse.json({ error: 'Rejection record not found' }, { status: 404 });
    }

    // Try to get order details if orderLine exists
    let orderInfo: any = null;
    if (rejection.orderLineId) {
      const orderLine = await prisma.orderLine.findUnique({
        where: { id: rejection.orderLineId },
        include: {
          order: {
            include: {
              shippingCustomer: true,
              billingCustomer: true,
              masterCustomer: true
            }
          }
        }
      });
      if (orderLine) {
        orderInfo = orderLine.order;
      }
    }

    return NextResponse.json({
      success: true,
      rejection: {
        ...rejection,
        order: orderInfo
      }
    });
  } catch (error: any) {
    console.error('Error fetching QC rejection detail:', error);
    return NextResponse.json({ error: error.message || 'Error fetching QC rejection' }, { status: 500 });
  }
}
