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

export class LeaguesController {
  async getLeaguesBySport(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { sportId } = sportIdParamSchema.parse(req.params);
      const query = leaguesQuerySchema.parse(req.query);

      // Verify sport exists
      const sport = await sportsService.getSportById(sportId);
      if (!sport) {
        throw new ApiError(404, 'Sport not found', 'SPORT_NOT_FOUND');
      }

      const leagues = await leaguesService.getLeaguesBySportId(sportId, query.isActive);
      res.json({ leagues });
    } catch (error) {
      next(error);
    }
  }

  async getLeagueById(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { leagueId } = leagueIdParamSchema.parse(req.params);
      const league = await leaguesService.getLeagueById(leagueId);

      if (!league) {
        throw new ApiError(404, 'League not found', 'LEAGUE_NOT_FOUND');
      }

      res.json({ league });
    } catch (error) {
      next(error);
    }
  }
}

export const leaguesController = new LeaguesController();
