// Bank Reconciliation API Route
export const dynamic = 'force-dynamic';

import { NextRequest, NextResponse } from 'next/server';
import { 
  runReconciliation, 
  getReconciliationStats, 
  getRecentReconciliations,
  resolveDiscrepancy 
} from '@/lib/order-to-cash/reconciliation';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const action = searchParams.get('action') || 'stats';
    
    if (action === 'stats') {
      const stats = await getReconciliationStats();
      return NextResponse.json(stats);
    } else if (action === 'recent') {
      const limit = parseInt(searchParams.get('limit') || '20');
      const reconciliations = await getRecentReconciliations(limit);
      return NextResponse.json(reconciliations);
    }
    
    return NextResponse.json({ error: 'Invalid action' }, { status: 400 });
  } catch (error) {
    console.error('[Reconciliation API] Error:', error);
    return NextResponse.json(
      { error: 'Failed to fetch reconciliation data' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { action, startDate, endDate, reconciliationId, resolution, resolvedBy } = body;
    
    if (action === 'run') {
      const start = startDate ? new Date(startDate) : undefined;
      const end = endDate ? new Date(endDate) : undefined;
      
      const results = await runReconciliation(start, end);
      
      return NextResponse.json({
        success: true,
        reconciliations: results.length,
        results,
        timestamp: new Date().toISOString(),
      });
    } else if (action === 'resolve') {
      if (!reconciliationId || !resolution || !resolvedBy) {
        return NextResponse.json(
          { error: 'Missing required fields' },
          { status: 400 }
        );
      }
      
      await resolveDiscrepancy(reconciliationId, resolution, resolvedBy);
      
      return NextResponse.json({
        success: true,
        message: 'Discrepancy resolved',
      });
    }
    
    return NextResponse.json({ error: 'Invalid action' }, { status: 400 });
  } catch (error) {
    console.error('[Reconciliation API] Error:', error);
    return NextResponse.json(
      { error: 'Failed to process reconciliation' },
      { status: 500 }
    );
  }
}
