import { LeagueModel } from '../models';
import { jsonStore } from '../data/json-store';
import { League } from '../types';
import { config } from '../config/env';
import { formatLeague } from '../utils/response-formatter';

export class LeaguesService {
  async getLeaguesBySportId(sportId: number, isActive?: boolean): Promise<League[]> {
    if (config.useJsonStore) {
      return jsonStore.getLeaguesBySportId(sportId, isActive).map(formatLeague);
    }

    const filter: Record<string, unknown> = { sportId };
    if (isActive !== undefined) {
      filter.isActive = isActive;
    }

    const leagues = await LeagueModel.find(filter).sort({ leagueName: 1 });
    return leagues.map(l => formatLeague(l.toJSON()));
  }

  async getLeagueById(leagueId: number): Promise<League | null> {
    if (config.useJsonStore) {
      const league = jsonStore.getLeagueById(leagueId);
      return league ? formatLeague(league) : null;
    }

    const league = await LeagueModel.findOne({ id: leagueId });
    return league ? formatLeague(league.toJSON()) : null;
  }
}

export const leaguesService = new LeaguesService();
