// Expense Categorization API
export const dynamic = 'force-dynamic';

import { NextRequest, NextResponse } from 'next/server';
import {
  categorizeExpense,
  processUncategorizedExpenses,
  getExpenseStats,
} from '@/lib/order-to-cash/expense-categorizer';
import prisma from '@/lib/db';

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 getExpenseStats();
        return NextResponse.json(stats);
      
      case 'recent':
        const limit = parseInt(searchParams.get('limit') || '20');
        const expenses = await prisma.expense.findMany({
          take: limit,
          orderBy: { date: 'desc' },
        });
        return NextResponse.json({ expenses });
      
      case 'flagged':
        const flagged = await prisma.expense.findMany({
          where: { status: 'flagged' },
          orderBy: { date: 'desc' },
        });
        return NextResponse.json({ flagged });
      
      default:
        return NextResponse.json({ error: 'Invalid action' }, { status: 400 });
    }
  } catch (error) {
    console.error('[Expenses API] Error:', error);
    return NextResponse.json({ error: 'Failed to fetch expense data' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { action, expenseId, description, amount, vendor, date } = body;
    
    switch (action) {
      case 'categorize':
        if (!expenseId) {
          return NextResponse.json({ error: 'Missing expenseId' }, { status: 400 });
        }
        const result = await categorizeExpense(expenseId, true);
        return NextResponse.json({ success: true, ...result });
      
      case 'process-all':
        const results = await processUncategorizedExpenses();
        return NextResponse.json({
          success: true,
          processed: results.length,
          results,
        });
      
      case 'create':
        if (!description || !amount) {
          return NextResponse.json({ error: 'Missing description or amount' }, { status: 400 });
        }
        const expense = await prisma.expense.create({
          data: {
            description,
            amount,
            vendor: vendor || null,
            date: date ? new Date(date) : new Date(),
            status: 'pending',
          },
        });
        // Auto-categorize
        const catResult = await categorizeExpense(expense.id, true);
        return NextResponse.json({ success: true, expense: catResult });
      
      case 'review':
        if (!expenseId) {
          return NextResponse.json({ error: 'Missing expenseId' }, { status: 400 });
        }
        await prisma.expense.update({
          where: { id: expenseId },
          data: { status: 'reviewed' },
        });
        return NextResponse.json({ success: true, message: 'Expense marked as reviewed' });
      
      default:
        return NextResponse.json({ error: 'Invalid action' }, { status: 400 });
    }
  } catch (error) {
    console.error('[Expenses API] Error:', error);
    return NextResponse.json({ error: 'Failed to process expense action' }, { status: 500 });
  }
}
