import { db } from '@/lib/prisma';
import type { AppContext } from '@/types/hono';

type DeletePlanParams = { code: string };

export async function deletePlanHandler(c: AppContext) {
  const { code } = c.req.valid('param' as never) as DeletePlanParams;

  const existing = await db.plan.findUnique({
    where: { code },
    include: {
      _count: {
        select: { complexes: true },
      },
    },
  });

  if (!existing) {
    return c.json({ message: 'Plan no encontrado.' }, 404);
  }

  if (existing._count.complexes > 0) {
    return c.json({ message: 'No se puede eliminar un plan que tiene complejos asignados.' }, 409);
  }

  await db.plan.delete({
    where: { code },
  });

  return c.json({ message: 'Plan eliminado correctamente.' });
}
