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

// 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, { 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 }
    );
  }

  // Upsert goal for target + period
  const existingGoal = await prisma.goal.findFirst({
    where: {
      targetType,
      targetId: parseInt(targetId),
      period
    }
  });

  let goal;
  if (existingGoal) {
    goal = await prisma.goal.update({
      where: { id: existingGoal.id },
      data: { amount: parseFloat(amount) }
    });
  } else {
    goal = await prisma.goal.create({
      data: {
        targetType,
        targetId: parseInt(targetId),
        period,
        amount: parseFloat(amount)
      }
    });
  }

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