// Inventory Triggers API
export const dynamic = 'force-dynamic';

import { NextRequest, NextResponse } from 'next/server';
import {
  checkInventoryLevels,
  getReorderSuggestions,
  processAutoReorders,
  fulfillInventoryAlert,
  getInventoryStats,
} from '@/lib/order-to-cash/inventory-triggers';

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 getInventoryStats();
        return NextResponse.json(stats);
      
      case 'suggestions':
        const suggestions = await getReorderSuggestions();
        return NextResponse.json({ suggestions });
      
      default:
        return NextResponse.json({ error: 'Invalid action' }, { status: 400 });
    }
  } catch (error) {
    console.error('[Inventory API] Error:', error);
    return NextResponse.json({ error: 'Failed to fetch inventory data' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { action, alertId, quantity } = body;
    
    switch (action) {
      case 'check':
        const checkResults = await checkInventoryLevels();
        return NextResponse.json({
          success: true,
          alertsCreated: checkResults.length,
          results: checkResults,
        });
      
      case 'auto-reorder':
        const reorderResults = await processAutoReorders();
        return NextResponse.json({
          success: true,
          ...reorderResults,
        });
      
      case 'fulfill':
        if (!alertId || !quantity) {
          return NextResponse.json({ error: 'Missing alertId or quantity' }, { status: 400 });
        }
        await fulfillInventoryAlert(alertId, quantity);
        return NextResponse.json({ success: true, message: 'Alert fulfilled' });
      
      default:
        return NextResponse.json({ error: 'Invalid action' }, { status: 400 });
    }
  } catch (error) {
    console.error('[Inventory API] Error:', error);
    return NextResponse.json({ error: 'Failed to process inventory action' }, { status: 500 });
  }
}
