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

setupLogRedaction();

export async function POST(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 body = await req.json();
    const { period, simulateOnly, results, uploaderId } = body;

    if (!period || !Array.isArray(results)) {
      return NextResponse.json({ error: 'Parámetros no válidos.' }, { status: 400 });
    }

    if (simulateOnly) {
      return NextResponse.json({
        success: true,
        code: 'SIMULATION_VERIFIED',
        results
      });
    }

    const prisma = getPrisma();

    // Perform database writes inside admin context transaction
    await prisma.$transaction(async (tx: any) => {
      await tx.$executeRawUnsafe(`SET LOCAL app.current_user_role = 'admin';`);

      // Delete existing non-approved settlements for this period
      const settlementsToDelete = await tx.settlement.findMany({
        where: {
          period,
          status: { in: ['PENDING', 'SIMULATED', 'REJECTED'] }
        }
      });

      const idsToDelete = settlementsToDelete.map((s: any) => s.id);
      if (idsToDelete.length > 0) {
        // Delete child adjustment records first
        await tx.settlement.deleteMany({
          where: {
            originalSettlementId: { in: idsToDelete }
          }
        });
        // Delete main records
        await tx.settlement.deleteMany({
          where: {
            id: { in: idsToDelete }
          }
        });
      }

      // Insert new settlements
      for (const item of results) {
        const createdMain = await tx.settlement.create({
          data: {
            ...item.main,
            aiAudited: item.aiAudited || false,
            aiAuditNotes: item.aiAuditNotes || null
          }
        });

        for (const adj of item.adjustments) {
          await tx.settlement.create({
            data: {
              ...adj,
              // Adjustments are sub-settlements linked to past periods
            }
          });
        }

        // Write audit log
        await tx.auditLog.create({
          data: {
            userId: uploaderId || 1, // fallback to admin user ID 1
            action: 'CREATE',
            targetTable: 'settlements',
            targetId: createdMain.id,
            newValue: item.main
          }
        });
      }
    });

    return NextResponse.json({
      success: true,
      code: 'SETTLEMENTS_SAVED'
    });
  } catch (err: any) {
    console.error('save-settlements error:', err);
    return NextResponse.json({ error: err.message || 'Error al guardar liquidaciones.' }, { status: 500 });
  }
}
