import { SportModel } from '../models';
import { jsonStore } from '../data/json-store';
import { Sport } from '../types';
import { config } from '../config/env';
import { formatSport } from '../utils/response-formatter';

export class SportsService {
  async getAllSports(isActive?: boolean): Promise<Sport[]> {
    if (config.useJsonStore) {
      return jsonStore.getSports(isActive).map(formatSport);
    }

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

    const sports = await SportModel.find(filter).sort({ sportName: 1 });
    return sports.map(s => formatSport(s.toJSON()));
  }

  async getSportById(sportId: number): Promise<Sport | null> {
    if (config.useJsonStore) {
      const sport = jsonStore.getSportById(sportId);
      return sport ? formatSport(sport) : null;
    }

    const sport = await SportModel.findOne({ id: sportId });
    return sport ? formatSport(sport.toJSON()) : null;
  }
}

export const sportsService = new SportsService();
