// Accounts Payable API
export const dynamic = 'force-dynamic';

import { NextRequest, NextResponse } from 'next/server';
import {
  intakeInvoice,
  approveInvoice,
  processScheduledPayments,
  getAPStats,
  getRecentInvoices,
} from '@/lib/order-to-cash/ap-automation';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const action = searchParams.get('action') || 'stats';
    
    switch (action) {
      case 'stats':
        const stats = await getAPStats();
        return NextResponse.json(stats);
      
      case 'invoices':
        const limit = parseInt(searchParams.get('limit') || '20');
        const invoices = await getRecentInvoices(limit);
        return NextResponse.json({ invoices });
      
      default:
        return NextResponse.json({ error: 'Invalid action' }, { status: 400 });
    }
  } catch (error) {
    console.error('[AP API] Error:', error);
    return NextResponse.json({ error: 'Failed to fetch AP data' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { action } = body;
    
    switch (action) {
      case 'intake':
        const { invoiceNumber, vendorName, vendorEmail, amount, dueDate, description, lineItems, category } = body;
        if (!invoiceNumber || !vendorName || !amount || !dueDate) {
          return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
        }
        const intakeResult = await intakeInvoice({
          invoiceNumber,
          vendorName,
          vendorEmail,
          amount,
          dueDate: new Date(dueDate),
          description,
          lineItems,
          category,
        });
        return NextResponse.json({ success: true, ...intakeResult });
      
      case 'approve':
        const { invoiceId, approvedBy, schedulePayDate } = body;
        if (!invoiceId || !approvedBy) {
          return NextResponse.json({ error: 'Missing invoiceId or approvedBy' }, { status: 400 });
        }
        await approveInvoice(invoiceId, approvedBy, schedulePayDate ? new Date(schedulePayDate) : undefined);
        return NextResponse.json({ success: true, message: 'Invoice approved' });
      
      case 'process-payments':
        const paymentResults = await processScheduledPayments();
        return NextResponse.json({ success: true, ...paymentResults });
      
      default:
        return NextResponse.json({ error: 'Invalid action' }, { status: 400 });
    }
  } catch (error) {
    console.error('[AP API] Error:', error);
    return NextResponse.json({ error: 'Failed to process AP action' }, { status: 500 });
  }
}
