import { NextRequest, NextResponse } from 'next/server';
import { getSession } from '@/lib/auth';
import { pgAddPurchaseCreditNote } from '@/lib/postgres/data-access';

export async function POST(req: NextRequest) {
  const session = await getSession();
  if (!session?.user?.id) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  try {
    const body = await req.json();
    const {
      creditScope,
      invoiceId,
      supplierId,
      supplierName,
      date,
      currencyCode,
      baseCurrencyCode,
      exchangeRate,
      warehouseId,
      items,
      subTotal,
      totalDiscount,
      taxAmount,
      grandTotal,
      grandTotalBase,
      reason,
      notes,
    } = body;

    const hasLinkedInvoice = Boolean(invoiceId && invoiceId !== '__supplier_balance__');
    if (!supplierId || !supplierName || !date || !reason) {
      return NextResponse.json(
        { error: 'Missing required fields' },
        { status: 400 }
      );
    }

    if (hasLinkedInvoice && !invoiceId) {
      return NextResponse.json(
        { error: 'Linked invoice is required for this credit note type' },
        { status: 400 }
      );
    }

    if (!grandTotal || Number(grandTotal) <= 0) {
      return NextResponse.json(
        { error: 'Credit note amount must be greater than zero' },
        { status: 400 }
      );
    }

    const creditNote = await pgAddPurchaseCreditNote({
      creditScope,
      invoiceId,
      supplierId,
      supplierName,
      date,
      currencyCode,
      baseCurrencyCode,
      exchangeRate,
      warehouseId,
      items: Array.isArray(items) ? items : [],
      subTotal,
      totalDiscount,
      taxAmount,
      grandTotal,
      grandTotalBase,
      reason,
      notes,
      createdBy: session.user.id,
    });

    return NextResponse.json(creditNote, { status: 201 });
  } catch (error: any) {
    if (error.message === 'CREDIT_NOTE_EXCEEDS_INVOICE') {
      return NextResponse.json(
        { error: 'Credit note total exceeds invoice amount' },
        { status: 409 }
      );
    }

    if (error.message === 'CREDIT_NOTE_AMOUNT_INVALID') {
      return NextResponse.json(
        { error: 'Credit note amount must be greater than zero' },
        { status: 400 }
      );
    }

    console.error('Error creating credit note:', error);
    return NextResponse.json(
      { error: error.message || 'Failed to create credit note' },
      { status: 500 }
    );
  }
}
