import { LeaguesService } from './leagues.service';
import { SportsService } from './sports.service';

// Force JSON store mode for tests
process.env.USE_JSON_STORE = 'true';

describe('LeaguesService', () => {
  let leaguesService: LeaguesService;
  let sportsService: SportsService;

  beforeAll(() => {
    leaguesService = new LeaguesService();
    sportsService = new SportsService();
  });

  describe('getLeaguesBySportId', () => {
    it('should return leagues for a sport', async () => {
      const sports = await sportsService.getAllSports();
      if (sports.length > 0) {
        const leagues = await leaguesService.getLeaguesBySportId(sports[0].id);

        expect(Array.isArray(leagues)).toBe(true);
      }
    });

    it('should return leagues sorted by name', async () => {
      const sports = await sportsService.getAllSports();
      if (sports.length > 0) {
        const leagues = await leaguesService.getLeaguesBySportId(sports[0].id);

        if (leagues.length > 1) {
          const names = leagues.map(l => l.leagueName);
          const sorted = [...names].sort();
          expect(names).toEqual(sorted);
        }
      }
    });

    it('should filter by isActive', async () => {
      const sports = await sportsService.getAllSports();
      if (sports.length > 0) {
        const leagues = await leaguesService.getLeaguesBySportId(sports[0].id, true);

        expect(leagues.every(l => l.isActive === true)).toBe(true);
      }
    });

    it('should return empty array for non-existent sport', async () => {
      const leagues = await leaguesService.getLeaguesBySportId(99999);

      expect(leagues).toEqual([]);
    });

    it('should return leagues with correct structure', async () => {
      const sports = await sportsService.getAllSports();
      if (sports.length > 0) {
        const leagues = await leaguesService.getLeaguesBySportId(sports[0].id);

        if (leagues.length > 0) {
          const league = leagues[0];
          expect(league).toHaveProperty('id');
          expect(league).toHaveProperty('sportId');
          expect(league).toHaveProperty('sportName');
          expect(league).toHaveProperty('leagueName');
          expect(league).toHaveProperty('leagueLogo');
          expect(league).toHaveProperty('isActive');
        }
      }
    });
  });

  describe('getLeagueById', () => {
    it('should return a league by ID', async () => {
      const sports = await sportsService.getAllSports();
      if (sports.length > 0) {
        const leagues = await leaguesService.getLeaguesBySportId(sports[0].id);
        if (leagues.length > 0) {
          const league = await leaguesService.getLeagueById(leagues[0].id);

          expect(league).not.toBeNull();
          expect(league?.id).toBe(leagues[0].id);
        }
      }
    });

    it('should return null for non-existent ID', async () => {
      const league = await leaguesService.getLeagueById(99999);

      expect(league).toBeNull();
    });
  });
});
