import { NextRequest, NextResponse } from 'next/server';
import { getPrisma } from '@/lib/db';
import { verifyN8nSignature } from '@/lib/n8n-auth';
import { setupLogRedaction } from '@/lib/log-redactor';

setupLogRedaction();

function getPastPeriods(period: string): string[] {
  const [yearStr, monthStr] = period.split('-');
  const year = parseInt(yearStr);
  const month = parseInt(monthStr);

  const past: string[] = [];
  for (let offset = 1; offset <= 2; offset++) {
    let m = month - offset;
    let y = year;
    if (m <= 0) {
      m += 12;
      y -= 1;
    }
    const mStr = m.toString().padStart(2, '0');
    past.push(`${y}-${mStr}`);
  }
  return past;
}

export async function GET(req: NextRequest) {
  try {
    const signature = req.headers.get('x-n8n-signature');
    if (!verifyN8nSignature(signature)) {
      return NextResponse.json({ error: 'No autorizado. Firma no válida.' }, { status: 401 });
    }

    const { searchParams } = req.nextUrl;
    const period = searchParams.get('period');

    if (!period || !/^\d{4}-\d{2}$/.test(period)) {
      return NextResponse.json(
        { error: 'El período es obligatorio y debe tener formato YYYY-MM.' },
        { status: 400 }
      );
    }

    const prisma = getPrisma();

    // Query all entities inside admin context to satisfy active RLS policies
    const data = await prisma.$transaction(async (tx: any) => {
      await tx.$executeRawUnsafe(`SET LOCAL app.current_user_role = 'admin';`);

      const collaborators = await tx.user.findMany({
        where: { role: 'collaborator', status: 'ACTIVE' },
        include: { hotel: true }
      });

      const activePlans = await tx.compensationPlan.findMany({
        where: { status: 'ACTIVE' },
        include: { rules: true }
      });

      const goals = await tx.goal.findMany({
        where: { period }
      });

      const salesResults = await tx.salesResult.findMany({
        where: { period }
      });

      const pastPeriods = getPastPeriods(period);

      const approvedPastSettlements = await tx.settlement.findMany({
        where: {
          period: { in: pastPeriods },
          status: 'APPROVED',
          originalSettlementId: null
        }
      });

      const pastSalesResults = await tx.salesResult.findMany({
        where: {
          period: { in: pastPeriods }
        }
      });

      const pastGoals = await tx.goal.findMany({
        where: {
          period: { in: pastPeriods }
        }
      });

      return {
        collaborators,
        activePlans,
        goals,
        salesResults,
        pastPeriods,
        approvedPastSettlements,
        pastSalesResults,
        pastGoals
      };
    });

    return NextResponse.json({
      success: true,
      ...data
    });
  } catch (err: any) {
    console.error('fetch-calculation-data error:', err);
    return NextResponse.json({ error: err.message || 'Error al obtener datos.' }, { status: 500 });
  }
}
