import League from '../models/League.js';
import Season from '../models/Season.js';
import SeasonService from './seasonService.js';
import { devLog } from '../utils/logger.js';

class LeagueService {
  static async getAllLeaguesByClub(clubId, seasonId = null) {
    try {
      
      // Wenn keine Saison angegeben, verwende die aktuelle
      if (!seasonId) {
        const currentSeason = await SeasonService.getOrCreateCurrentSeason();
        seasonId = currentSeason.id;
      }
      
      const leagues = await League.findAll({
        where: { clubId, seasonId },
        include: [
          {
            model: Season,
            as: 'season',
            attributes: ['id', 'season']
          }
        ],
        order: [['name', 'ASC']]
      });
      return leagues;
    } catch (error) {
      console.error('[LeagueService.getAllLeaguesByClub] - Error:', error);
      throw error;
    }
  }

  static async getLeagueById(leagueId) {
    try {
      const league = await League.findByPk(leagueId, {
        include: [
          {
            model: Season,
            as: 'season',
            attributes: ['id', 'season']
          }
        ]
      });
      return league;
    } catch (error) {
      console.error('[LeagueService.getLeagueById] - Error:', error);
      throw error;
    }
  }

  static async createLeague(leagueData) {
    try {
      
      // Wenn keine Saison angegeben, verwende die aktuelle
      if (!leagueData.seasonId) {
        const currentSeason = await SeasonService.getOrCreateCurrentSeason();
        leagueData.seasonId = currentSeason.id;
      }
      
      const league = await League.create(leagueData);
      return league;
    } catch (error) {
      console.error('[LeagueService.createLeague] - Error:', error);
      throw error;
    }
  }

  static async updateLeague(leagueId, updateData) {
    try {
      const [updatedRowsCount] = await League.update(updateData, {
        where: { id: leagueId }
      });
      return updatedRowsCount > 0;
    } catch (error) {
      console.error('[LeagueService.updateLeague] - Error:', error);
      throw error;
    }
  }

  static async deleteLeague(leagueId) {
    try {
      const deletedRowsCount = await League.destroy({
        where: { id: leagueId }
      });
      return deletedRowsCount > 0;
    } catch (error) {
      console.error('[LeagueService.deleteLeague] - Error:', error);
      throw error;
    }
  }
}

export default LeagueService;
