import { auth } from "@/lib/auth";
import { db } from "@/lib/db";
import { gastosServicios } from "@/lib/schema";
import { eq, desc } from "drizzle-orm";

export async function GET(req: Request, { params }: { params: Promise<{ id: string }> }) {
  const session = await auth();
  if (!session) return Response.json({ error: "Unauthorized" }, { status: 401 });

  const { id } = await params;
  const numId = parseInt(id);
  if (isNaN(numId) || numId <= 0) return Response.json({ error: "Invalid ID" }, { status: 400 });

  const rows = await db.select()
    .from(gastosServicios)
    .where(eq(gastosServicios.servicioId, numId))
    .orderBy(desc(gastosServicios.periodo));
  return Response.json(rows);
}

export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {
  const session = await auth();
  if (!session) return Response.json({ error: "Unauthorized" }, { status: 401 });
  if (session.user.role !== "admin") return Response.json({ error: "Forbidden" }, { status: 403 });

  const { id } = await params;
  const numId = parseInt(id);
  if (isNaN(numId) || numId <= 0) return Response.json({ error: "Invalid ID" }, { status: 400 });
  const body = await req.json();
  const { periodo, montoFacturado, montoPagado, fechaPago, notas } = body;

  if (!periodo || !/^\d{4}-\d{2}$/.test(periodo)) {
    return Response.json({ error: "Período inválido (formato: YYYY-MM)" }, { status: 400 });
  }
  if (typeof montoFacturado !== "number" || montoFacturado <= 0) {
    return Response.json({ error: "Monto facturado debe ser un número positivo" }, { status: 400 });
  }

  const [newEntry] = await db.insert(gastosServicios).values({
    servicioId: numId,
    periodo,
    montoFacturado,
    montoPagado: montoPagado || 0,
    fechaPago,
    notas,
  }).returning();

  return Response.json(newEntry, { status: 201 });
}
