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

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

  const whereClause: any = {};
  if (targetType) whereClause.targetType = targetType;
  if (period) whereClause.period = period;

  const goals = await prisma.goal.findMany({
    where: whereClause,
    orderBy: { createdAt: 'desc' }
  });

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

// POST: Create or Update goal for a period (restricted to ADMIN and DIRECTOR)
export const POST = withAuth(async (req, { session, prisma }) => {
  const body = await req.json();
  const { targetType, targetId, period, amount } = body;

  if (!targetType || targetId === undefined || !period || amount === undefined) {
    return NextResponse.json(
      { error: 'targetType, targetId, period y amount son campos obligatorios.' },
      { status: 400 }
    );
  }

  const result = await prisma.$transaction(async (tx: any) => {
    // Upsert goal for target + period
    const existingGoal = await tx.goal.findFirst({
      where: {
        targetType,
        targetId: parseInt(targetId),
        period
      }
    });

    let goal;
    if (existingGoal) {
      goal = await tx.goal.update({
        where: { id: existingGoal.id },
        data: { amount: parseFloat(amount) }
      });

      await createAuditLog(tx, {
        userId: session.userId,
        action: 'UPDATE',
        targetTable: 'goals',
        targetId: goal.id,
        previousValue: existingGoal,
        newValue: goal,
        ipAddress: req.headers.get('x-forwarded-for') || '127.0.0.1'
      });
    } else {
      goal = await tx.goal.create({
        data: {
          targetType,
          targetId: parseInt(targetId),
          period,
          amount: parseFloat(amount)
        }
      });

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

    return goal;
  });

  return NextResponse.json({ goal: result });
}, ['admin', 'director']);
