import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import { RomsController } from '../controllers/romsController';
import { linkGameSchema } from '../validators/romValidator';
import { ZodError } from 'zod';

async function romsRoutes(app: FastifyInstance) {
  /**
   * GET /api/roms
   * Listar todos los ROMs
   */
  app.get<{ Reply: any[] }>('/roms', async (request, reply) => {
    const roms = await RomsController.listRoms();
    return reply.code(200).send(roms);
  });

  /**
   * GET /api/roms/:id
   * Obtener un ROM por ID
   */
  app.get<{ Params: { id: string }; Reply: any }>('/roms/:id', async (request, reply) => {
    try {
      const rom = await RomsController.getRomById(request.params.id);
      return reply.code(200).send(rom);
    } catch (error) {
      if (error instanceof Error && error.message.includes('no encontrado')) {
        return reply.code(404).send({
          error: 'ROM no encontrado',
        });
      }
      throw error;
    }
  });

  /**
   * PUT /api/roms/:id/game
   * Vincular un juego a un ROM
   */
  app.put<{ Params: { id: string }; Body: any; Reply: any }>(
    '/roms/:id/game',
    async (request, reply) => {
      try {
        // Validar entrada con Zod
        const validated = linkGameSchema.parse(request.body);
        const rom = await RomsController.linkGameToRom(request.params.id, validated.gameId);
        return reply.code(200).send(rom);
      } catch (error) {
        if (error instanceof ZodError) {
          return reply.code(400).send({
            error: 'Validación fallida',
            details: error.errors,
          });
        }
        if (error instanceof Error) {
          if (error.message.includes('ROM no encontrado')) {
            return reply.code(404).send({
              error: 'ROM no encontrado',
            });
          }
          if (error.message.includes('Juego no encontrado')) {
            return reply.code(400).send({
              error: 'Game ID inválido o no encontrado',
            });
          }
        }
        throw error;
      }
    }
  );

  /**
   * DELETE /api/roms/:id
   * Eliminar un ROM
   */
  app.delete<{ Params: { id: string }; Reply: any }>('/roms/:id', async (request, reply) => {
    try {
      await RomsController.deleteRom(request.params.id);
      return reply.code(204).send();
    } catch (error) {
      if (error instanceof Error && error.message.includes('no encontrado')) {
        return reply.code(404).send({
          error: 'ROM no encontrado',
        });
      }
      throw error;
    }
  });
}

export default romsRoutes;

/**
 * Metadatos:
 * Autor: GitHub Copilot
 * Última actualización: 2026-02-11
 */
