import { ParticipantModel } from '../models';
import { jsonStore } from '../data/json-store';
import { Participant, ParticipantType } from '../types';
import { config } from '../config/env';
import { formatParticipant } from '../utils/response-formatter';

export class ParticipantsService {
  async getParticipantsByLeagueId(
    leagueId: number,
    type?: ParticipantType,
    isActive?: boolean
  ): Promise<Participant[]> {
    if (config.useJsonStore) {
      return jsonStore.getParticipantsByLeagueId(leagueId, type, isActive).map(formatParticipant);
    }

    const filter: Record<string, unknown> = { leagueIds: leagueId };

    if (type) {
      filter.participantType = type;
    }

    if (isActive !== undefined) {
      filter.isActive = isActive;
    }

    const participants = await ParticipantModel.find(filter).sort({ teamName: 1, fullName: 1 });
    return participants.map(p => formatParticipant(p.toJSON()));
  }
}

export const participantsService = new ParticipantsService();
