import { NextRequest, NextResponse } from 'next/server';
import * as z from 'zod';
import { pgReturnEndorsedIncomingCheck } from '@/lib/postgres/data-access';

const payloadSchema = z.object({
  checkId: z.string().trim().min(1),
  reason: z.string().trim().min(1),
  returnedDate: z.string().trim().optional(),
  bankFeeAmount: z.coerce.number().min(0).optional().default(0),
  chargeFeeToCustomer: z.boolean().optional().default(false),
  notes: z.string().trim().optional(),
});

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const parsed = payloadSchema.safeParse(body);
    if (!parsed.success) {
      return NextResponse.json({ error: 'Invalid payload' }, { status: 400 });
    }

    const payload = parsed.data;
    const result = await pgReturnEndorsedIncomingCheck({
      checkId: payload.checkId,
      reason: payload.reason,
      returnedDate: payload.returnedDate,
      bankFeeAmount: payload.bankFeeAmount,
      chargeFeeToCustomer: payload.chargeFeeToCustomer,
      notes: payload.notes,
      createdBy: 'system',
    });

    return NextResponse.json({
      success: true,
      message: 'Incoming check returned successfully',
      check: result.check,
      event: result.event,
      journalEntryId: result.journalEntryId,
    });
  } catch (error) {
    const message = error instanceof Error ? error.message : '';
    if (message === 'CHECK_NOT_FOUND') {
      return NextResponse.json({ error: 'Check not found' }, { status: 404 });
    }
    if (message === 'CHECK_ALREADY_RETURNED') {
      return NextResponse.json({ error: 'Check already returned' }, { status: 409 });
    }
    if (message === 'CHECK_NOT_ENDORSED_TO_SUPPLIER') {
      return NextResponse.json({ error: 'Only checks endorsed to suppliers can be returned from this flow' }, { status: 400 });
    }
    if (message === 'CHECK_RETURN_REASON_REQUIRED') {
      return NextResponse.json({ error: 'Return reason is required' }, { status: 400 });
    }
    if (message === 'SUPPLIER_NOT_FOUND') {
      return NextResponse.json({ error: 'Supplier linked to this endorsed check was not found' }, { status: 404 });
    }
    if (message === 'CUSTOMER_NOT_FOUND') {
      return NextResponse.json({ error: 'Customer linked to this check was not found' }, { status: 404 });
    }
    if (message === 'CHECK_RETURN_BALANCE_UPDATE_FAILED') {
      return NextResponse.json({ error: 'Failed to update customer/supplier balances while returning check' }, { status: 500 });
    }
    return NextResponse.json({ error: message || 'Failed to return incoming check' }, { status: 500 });
  }
}
