import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/db';
import { withPermission, isErrorResponse } from '@/lib/auth/api-guard';

export const dynamic = 'force-dynamic';

// GET - Fetch finance summary/accounts
export async function GET(request: NextRequest) {
  // Check permission
  const auth = await withPermission(request, { resource: 'finance', action: 'read' });
  if (isErrorResponse(auth)) return auth;

  try {
    const { searchParams } = new URL(request.url);
    const type = searchParams.get('type') || 'summary';

    if (type === 'accounts') {
      const accounts = await prisma.account.findMany({
        where: { isActive: true },
        orderBy: { code: 'asc' },
        include: { _count: { select: { transactions: true } } },
      });
      return NextResponse.json({ success: true, accounts });
    }

    if (type === 'transactions') {
      const limit = parseInt(searchParams.get('limit') || '50');
      const transactions = await prisma.transaction.findMany({
        take: limit,
        orderBy: { date: 'desc' },
        include: { account: { select: { name: true, code: true } } },
      });
      return NextResponse.json({ success: true, transactions });
    }

    if (type === 'invoices') {
      const invoices = await prisma.invoice.findMany({
        orderBy: { issueDate: 'desc' },
        take: 50,
      });
      return NextResponse.json({ success: true, invoices });
    }

    // Summary
    const [accounts, recentTransactions, invoices, budgets] = await Promise.all([
      prisma.account.findMany({ where: { isActive: true } }),
      prisma.transaction.findMany({ 
        take: 10, 
        orderBy: { date: 'desc' },
        include: { account: { select: { name: true, code: true } } }
      }),
      prisma.invoice.findMany({ take: 10, orderBy: { issueDate: 'desc' } }),
      prisma.budget.findMany({ where: { status: 'active' } }),
    ]);

    const totalAssets = accounts.filter((a: any) => a.type === 'asset').reduce((sum: number, a: any) => sum + a.balance, 0);
    const totalLiabilities = accounts.filter((a: any) => a.type === 'liability').reduce((sum: number, a: any) => sum + a.balance, 0);
    const totalRevenue = accounts.filter((a: any) => a.type === 'revenue').reduce((sum: number, a: any) => sum + a.balance, 0);
    const totalExpenses = accounts.filter((a: any) => a.type === 'expense').reduce((sum: number, a: any) => sum + a.balance, 0);

    const pendingInvoices = invoices.filter((i: any) => i.status === 'sent' || i.status === 'overdue');
    const overdueInvoices = invoices.filter((i: any) => i.status === 'overdue');

    // Filter out any transactions with missing account relations
    const validTransactions = recentTransactions.filter((tx: any) => tx.account && tx.account.name);

    return NextResponse.json({
      success: true,
      summary: {
        totalAssets,
        totalLiabilities,
        totalRevenue,
        totalExpenses,
        netIncome: totalRevenue - totalExpenses,
        netWorth: totalAssets - totalLiabilities,
        accountCount: accounts.length,
        pendingInvoicesCount: pendingInvoices.length,
        overdueInvoicesAmount: overdueInvoices.reduce((sum: number, i: any) => sum + (i.total - i.amountPaid), 0),
        activeBudgets: budgets.length,
        budgetUtilization: budgets.length > 0 
          ? (budgets.reduce((sum: number, b: any) => sum + b.spent, 0) / budgets.reduce((sum: number, b: any) => sum + b.amount, 0)) * 100 
          : 0,
      },
      recentTransactions: validTransactions,
      recentInvoices: invoices.slice(0, 5),
    });
  } catch (error) {
    console.error('Finance API error:', error);
    return NextResponse.json({ success: false, error: 'Failed to fetch finance data' }, { status: 500 });
  }
}

// POST - Create new account/transaction/invoice
export async function POST(request: NextRequest) {
  const auth = await withPermission(request, { resource: 'finance', action: 'write' });
  if (isErrorResponse(auth)) return auth;

  try {
    const body = await request.json();
    const { entity, data } = body;

    if (entity === 'account') {
      const account = await prisma.account.create({ data });
      return NextResponse.json({ success: true, account });
    }

    if (entity === 'transaction') {
      const transaction = await prisma.transaction.create({
        data,
        include: { account: true },
      });
      // Update account balance
      await prisma.account.update({
        where: { id: data.accountId },
        data: { balance: { increment: data.amount } },
      });
      return NextResponse.json({ success: true, transaction });
    }

    if (entity === 'invoice') {
      const invoice = await prisma.invoice.create({ data });
      return NextResponse.json({ success: true, invoice });
    }

    if (entity === 'budget') {
      const budget = await prisma.budget.create({ data });
      return NextResponse.json({ success: true, budget });
    }

    return NextResponse.json({ success: false, error: 'Invalid entity type' }, { status: 400 });
  } catch (error) {
    console.error('Finance POST error:', error);
    return NextResponse.json({ success: false, error: 'Failed to create record' }, { status: 500 });
  }
}
