import { NextRequest, NextResponse } from 'next/server';
import { randomUUID } from 'crypto';

import {
  pgGetChecksReceived,
  pgSaveChecksReceived,
  pgSaveJournalEntry,
  pgUpdateCustomerBalance,
} from '@/lib/postgres/data-access';

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { checkId, action, date, notes, rejectedReason } = body;

    if (!checkId || !action || !['cleared', 'rejected'].includes(action)) {
      return NextResponse.json({ error: 'Missing or invalid required fields' }, { status: 400 });
    }

    const checks = (await pgGetChecksReceived({ page: 1, pageSize: 5000 })).items as any[];
    const check = checks.find((c) => c.id === checkId);
    if (!check) {
      return NextResponse.json({ error: 'Check not found' }, { status: 404 });
    }

    if (check.status !== 'pending') {
      return NextResponse.json({ error: 'Only pending checks can be cleared or rejected' }, { status: 400 });
    }

    const actionDate = date || new Date().toISOString();
    const updatedCheck = {
      ...check,
      status: action,
      updatedAt: new Date().toISOString(),
      ...(action === 'cleared' ? { clearedDate: actionDate } : {}),
      ...(action === 'rejected' ? { rejectedDate: actionDate, rejectedReason: rejectedReason || '' } : {}),
      ...(notes ? { notes: check.notes ? `${check.notes}\n${notes}` : notes } : {}),
    };

    await pgSaveChecksReceived([updatedCheck]);

    const entryId = `je-${randomUUID()}`;
    const amount = Number(check.amount || 0);

    if (action === 'cleared') {
      // Dr 1010 Cash/Bank / Cr 1015 Incoming Checks
      await pgSaveJournalEntry([{
        id: entryId,
        date: actionDate,
        referenceType: 'payment',
        referenceId: `CHK-CLEARED-${checkId}`,
        description: `تأكيد صرف شيك رقم ${check.checkNumber} - ${check.customerName || ''}`,
        lines: [
          {
            accountId: '1010',
            accountCode: '1010',
            accountName: 'النقد في الصندوق / Cash at Bank',
            debit: amount,
            credit: 0,
            description: `استلام قيمة شيك رقم ${check.checkNumber}`,
          },
          {
            accountId: '1015',
            accountCode: '1015',
            accountName: 'شيكات واردة / Incoming Checks',
            debit: 0,
            credit: amount,
            description: `تصفية شيك رقم ${check.checkNumber}`,
          },
        ],
        createdBy: 'System',
        createdAt: new Date().toISOString(),
      }]);
    } else {
      // action === 'rejected'
      // Dr 1110 Customer AR / Cr 1015 Incoming Checks (reverses original receipt)
      await pgSaveJournalEntry([{
        id: entryId,
        date: actionDate,
        referenceType: 'payment',
        referenceId: `CHK-REJECTED-${checkId}`,
        description: `رفض شيك رقم ${check.checkNumber} - ${check.customerName || ''} - السبب: ${rejectedReason || ''}`,
        lines: [
          {
            accountId: '1110',
            accountCode: '1110',
            accountName: 'ذمم مدينة / Accounts Receivable',
            debit: amount,
            credit: 0,
            description: `إعادة إثبات ذمة العميل برفض شيك رقم ${check.checkNumber}`,
          },
          {
            accountId: '1015',
            accountCode: '1015',
            accountName: 'شيكات واردة / Incoming Checks',
            debit: 0,
            credit: amount,
            description: `رفض شيك رقم ${check.checkNumber}`,
          },
        ],
        createdBy: 'System',
        createdAt: new Date().toISOString(),
      }]);

      // Restore customer balance (re-debit them since check was rejected)
      if (check.customerId) {
        try {
          await pgUpdateCustomerBalance(check.customerId, amount);
        } catch {
          // Non-fatal: balance update failure doesn't block the status update
        }
      }
    }

    return NextResponse.json({ success: true, checkId, action, journalEntryId: entryId });
  } catch (error: any) {
    console.error('[mark-status] Error:', error);
    return NextResponse.json({ error: error?.message || 'Internal server error' }, { status: 500 });
  }
}
