// AR Dunning API Route
export const dynamic = 'force-dynamic';

import { NextRequest, NextResponse } from 'next/server';
import { processDunning, getDunningStats, getDunningHistory } from '@/lib/order-to-cash/dunning';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const action = searchParams.get('action') || 'stats';
    const arId = searchParams.get('arId');
    
    if (action === 'stats') {
      const stats = await getDunningStats();
      return NextResponse.json(stats);
    } else if (action === 'history') {
      const history = await getDunningHistory(arId || undefined);
      return NextResponse.json(history);
    }
    
    return NextResponse.json({ error: 'Invalid action' }, { status: 400 });
  } catch (error) {
    console.error('[Dunning API] Error:', error);
    return NextResponse.json(
      { error: 'Failed to fetch dunning data' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { autoSendEmails = true } = body;
    
    const results = await processDunning({
      level1DaysOverdue: 7,
      level2DaysOverdue: 14,
      level3DaysOverdue: 30,
      autoSendEmails,
    });
    
    return NextResponse.json({
      success: true,
      processed: results.length,
      results,
      timestamp: new Date().toISOString(),
    });
  } catch (error) {
    console.error('[Dunning API] Error:', error);
    return NextResponse.json(
      { error: 'Failed to process dunning' },
      { status: 500 }
    );
  }
}
