import { Prisma } from '@/generated/prisma/client';
import { getSportById, updateSport } from '@/modules/sport/services/sport.service';
import type { AppContext } from '@/types/hono';
import type { UpdateSportInput } from '@repo/api-contract';

type SportIdParams = { id: string };

export async function updateSportHandler(c: AppContext) {
  const { id } = c.req.valid('param' as never) as SportIdParams;
  const payload = c.req.valid('json' as never) as UpdateSportInput;

  const existing = await getSportById(id);

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

  try {
    const sport = await updateSport(id, payload);
    return c.json(sport);
  } catch (error) {
    if (error instanceof Prisma.PrismaClientKnownRequestError) {
      return c.json({ message: 'No se pudo actualizar el deporte.' }, 409);
    }
    throw error;
  }
}
