import { Request, Response, NextFunction } from 'express';
import { widgetTypesService } from '../services';
import { leaguesService } from '../services';
import { widgetTypesQuerySchema, leagueIdParamSchema } from '../validation/schemas';
import { ApiError } from '../middleware/error.middleware';

export class WidgetTypesController {
  async getWidgetTypes(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const query = widgetTypesQuerySchema.parse(req.query);

      const widgetTypes = await widgetTypesService.getWidgetTypes(
        query.sportId,
        query.leagueId,
        query.isActive
      );
      res.json({ widgetTypes });
    } catch (error) {
      next(error);
    }
  }

  async getWidgetTypesByLeague(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { leagueId } = leagueIdParamSchema.parse(req.params);
      const query = widgetTypesQuerySchema.parse(req.query);

      // Verify league exists
      const league = await leaguesService.getLeagueById(leagueId);
      if (!league) {
        throw new ApiError(404, 'League not found', 'LEAGUE_NOT_FOUND');
      }

      const widgetTypes = await widgetTypesService.getWidgetTypes(
        undefined,
        leagueId,
        query.isActive
      );
      res.json({ widgetTypes });
    } catch (error) {
      next(error);
    }
  }
}

export const widgetTypesController = new WidgetTypesController();
