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

// GET: Fetch all plans (accessible to all authenticated roles)
export const GET = withAuth(async (req, { prisma }) => {
  const { searchParams } = req.nextUrl;
  const status = searchParams.get('status');
  const code = searchParams.get('code');

  const whereClause: any = {};
  if (status) whereClause.status = status;
  if (code) whereClause.code = code;

  const plans = await prisma.compensationPlan.findMany({
    where: whereClause,
    include: {
      rules: true
    },
    orderBy: { createdAt: 'desc' }
  });

  return NextResponse.json({ plans });
});

// POST: Create a new plan (restricted to admin and director)
export const POST = withAuth(async (req, { session, prisma }) => {
  const body = await req.json();
  const { name, code, validityStart, validityEnd, type, formula, metaAmount, percentageRate, maxCap, status } = body;

  // Validate mandatory fields
  if (!name || !code || !validityStart || !type) {
    return NextResponse.json(
      { error: 'El nombre, código, fecha de inicio de vigencia y tipo son campos obligatorios.' },
      { status: 400 }
    );
  }

  const plan = await prisma.$transaction(async (tx: any) => {
    const p = await tx.compensationPlan.create({
      data: {
        name,
        code,
        validityStart: new Date(validityStart),
        validityEnd: validityEnd ? new Date(validityEnd) : null,
        type,
        formula: formula || null,
        metaAmount: metaAmount !== undefined ? parseFloat(metaAmount) : null,
        percentageRate: percentageRate !== undefined ? parseFloat(percentageRate) : null,
        maxCap: maxCap !== undefined ? parseFloat(maxCap) : null,
        status: status || 'DRAFT',
        version: 1,
        createdBy: session.userId
      }
    });

    await createAuditLog(tx, {
      userId: session.userId,
      action: 'CREATE',
      targetTable: 'compensation_plans',
      targetId: p.id,
      newValue: p,
      ipAddress: req.headers.get('x-forwarded-for') || '127.0.0.1'
    });

    return p;
  });

  return NextResponse.json({ plan }, { status: 201 });
}, ['admin', 'director']);
