// ${VOCAB.factory} Integration API
export const dynamic = 'force-dynamic';

import { NextRequest, NextResponse } from 'next/server';
import {
  queueDarkFactoryJob,
  processQueuedJobs,
  getJobStats,
  getRecentJobs,
  triggerInventoryReorderReport,
  triggerARAgingReport,
  triggerExpenseAnalysis,
  JobType,
  TriggerSource,
} from '@/lib/order-to-cash/dark-factory-integration';
import { VOCAB } from '@/lib/white-label/constants';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const action = searchParams.get('action') || 'stats';
    const limit = parseInt(searchParams.get('limit') || '20');
    
    if (action === 'stats') {
      const stats = await getJobStats();
      return NextResponse.json(stats);
    }
    
    if (action === 'recent') {
      const jobs = await getRecentJobs(limit);
      return NextResponse.json(jobs);
    }
    
    return NextResponse.json({ error: 'Invalid action' }, { status: 400 });
  } catch (error) {
    console.error(`[${VOCAB.factory} API] Error:`, error);
    return NextResponse.json({ error: `Failed to fetch ${VOCAB.factory} data` }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { action } = body;
    
    if (action === 'queue') {
      const { jobType, triggerSource, triggerId, input } = body;
      const jobId = await queueDarkFactoryJob({
        jobType: jobType as JobType,
        triggerSource: triggerSource as TriggerSource,
        triggerId,
        input: input || {},
      });
      return NextResponse.json({ success: true, jobId });
    }
    
    if (action === 'process') {
      const result = await processQueuedJobs();
      return NextResponse.json({ success: true, ...result });
    }
    
    if (action === 'trigger-inventory-report') {
      const { alertId, productName, currentStock } = body;
      const jobId = await triggerInventoryReorderReport(alertId, productName, currentStock);
      return NextResponse.json({ success: true, jobId });
    }
    
    if (action === 'trigger-ar-report') {
      const jobId = await triggerARAgingReport();
      return NextResponse.json({ success: true, jobId });
    }
    
    if (action === 'trigger-expense-analysis') {
      const jobId = await triggerExpenseAnalysis();
      return NextResponse.json({ success: true, jobId });
    }
    
    return NextResponse.json({ error: 'Invalid action' }, { status: 400 });
  } catch (error) {
    console.error(`[${VOCAB.factory} API] Error:`, error);
    return NextResponse.json({ error: `Failed to process ${VOCAB.factory} action` }, { status: 500 });
  }
}
