import { db } from '@/lib/prisma';
import type { AppContext } from '@/types/hono';
import type { AdminCreatePlanInput } from '@repo/api-contract';

export async function createPlanHandler(c: AppContext) {
  const body = c.req.valid('json' as never) as AdminCreatePlanInput;

  const existing = await db.plan.findUnique({
    where: { code: body.code },
  });

  if (existing) {
    return c.json({ message: 'Ya existe un plan con ese código.' }, 409);
  }

  const plan = await db.plan.create({
    data: {
      code: body.code,
      name: body.name,
      price: body.price,
      rules: body.rules,
    },
  });

  return c.json(
    {
      code: plan.code,
      name: plan.name,
      price: Number(plan.price),
      rules: plan.rules,
    },
    201
  );
}
