import { NextRequest, NextResponse } from 'next/server';
import { withAuth } from '@/lib/api-guards';

// GET: Fetch settlements (accessible to authenticated users, filtered by DB-level RLS)
export const GET = withAuth(async (req, { prisma }) => {
  try {
    const { searchParams } = req.nextUrl;
    const period = searchParams.get('period');
    const status = searchParams.get('status');

    const userId = searchParams.get('userId');

    const whereClause: any = {};
    if (period) whereClause.period = period;
    if (status) whereClause.status = status;
    if (userId) whereClause.userId = parseInt(userId);

    const settlements = await prisma.settlement.findMany({
      where: whereClause,
      include: {
        colaborador: {
          select: {
            id: true,
            username: true,
            email: true,
            area: true,
            hotel: {
              select: {
                name: true,
                code: true
              }
            }
          }
        },
        plan: {
          select: {
            id: true,
            name: true,
            code: true,
            version: true
          }
        }
      },
      orderBy: { createdAt: 'desc' }
    });

    return NextResponse.json({ settlements });
  } catch (err: any) {
    console.error('Failed to fetch settlements:', err);
    return NextResponse.json({ error: 'Failed to fetch settlements' }, { status: 500 });
  }
});
