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

export const POST = withAuth(async (req, { session, prisma, params }) => {
  try {
    const unwrappedParams = await params;
    const id = parseInt(unwrappedParams.id);

    if (isNaN(id)) {
      return NextResponse.json({ error: 'ID no válido.' }, { status: 400 });
    }

    // Bypass RLS to check actual existence and regions
    const systemPrisma = getPrisma(null);
    const { settlement, leaderUser } = await systemPrisma.$transaction(async (tx: any) => {
      await tx.$executeRawUnsafe(`SET LOCAL app.current_user_role = 'admin';`);
      const s = await tx.settlement.findUnique({
        where: { id },
        include: { colaborador: { include: { hotel: true } } }
      });
      let l = null;
      if (session.role === 'commercial_leader') {
        l = await tx.user.findUnique({
          where: { id: session.userId },
          include: { hotel: true }
        });
      }
      return { settlement: s, leaderUser: l };
    });

    if (!settlement) {
      return NextResponse.json({ error: 'Liquidación no encontrada.' }, { status: 404 });
    }

    if (session.role === 'commercial_leader') {
      if (!leaderUser || leaderUser.hotel.regionId !== settlement.colaborador.hotel.regionId) {
        return NextResponse.json(
          { error: 'Acceso prohibido. No puede aprobar liquidaciones de otras regiones.' },
          { status: 403 }
        );
      }
    }

    // Update the settlement status using the session-bound prisma client to respect RLS
    const updated = await prisma.settlement.update({
      where: { id },
      data: {
        status: 'APPROVED',
        approvedBy: session.userId,
        approvedAt: new Date()
      }
    });

    // Write audit log using system client inside a transaction to satisfy RLS select policy
    await systemPrisma.$transaction(async (tx: any) => {
      await tx.$executeRawUnsafe(`SET LOCAL app.current_user_role = 'admin';`);
      await tx.auditLog.create({
        data: {
          userId: session.userId,
          action: 'APPROVE',
          targetTable: 'settlements',
          targetId: id,
          previousValue: JSON.parse(JSON.stringify(settlement)),
          newValue: JSON.parse(JSON.stringify(updated))
        }
      });
    });

    // Create a notification for the collaborator
    await systemPrisma.notification.create({
      data: {
        userId: settlement.userId,
        title: 'Liquidación Aprobada',
        message: `Tu liquidación para el período ${settlement.period} ha sido aprobada.`,
        type: 'PUSH',
        status: 'UNREAD'
      }
    });

    return NextResponse.json({ success: true, settlement: updated });
  } catch (err: any) {
    console.error('Approve settlement error:', err);
    return NextResponse.json(
      { error: err.message || 'Error al aprobar la liquidación.' },
      { status: 500 }
    );
  }
}, ['commercial_leader', 'admin']);
