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

type UpdatePlanParams = { code: string };

export async function updatePlanHandler(c: AppContext) {
  const { code } = c.req.valid('param' as never) as UpdatePlanParams;
  const body = c.req.valid('json' as never) as AdminUpdatePlanInput;

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

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

  const plan = await db.plan.update({
    where: { code },
    data: {
      ...(body.name !== undefined && { name: body.name }),
      ...(body.price !== undefined && { price: body.price }),
      ...(body.rules !== undefined && { rules: body.rules }),
      lastUpdatedAt: new Date(),
    },
  });

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