import type { Logger } from '@core/shared/domain/Logger';
import { Result } from '@core/shared/domain/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { SeasonRepository } from '../../domain/repositories/SeasonRepository';

export interface PublishLeagueSeasonScheduleInput {
  leagueId: string;
  seasonId: string;
}

export type PublishLeagueSeasonScheduleResult = {
  success: true;
  seasonId: string;
  published: true;
};

export type PublishLeagueSeasonScheduleErrorCode =
  | 'SEASON_NOT_FOUND'
  | 'REPOSITORY_ERROR';

export class PublishLeagueSeasonScheduleUseCase {
  constructor(
    private readonly seasonRepository: SeasonRepository,
    private readonly logger: Logger,
  ) {}

  async execute(
    input: PublishLeagueSeasonScheduleInput,
  ): Promise<
    Result<
      PublishLeagueSeasonScheduleResult,
      ApplicationErrorCode<PublishLeagueSeasonScheduleErrorCode, { message: string }>
    >
  > {
    this.logger.debug('Publishing league season schedule', {
      leagueId: input.leagueId,
      seasonId: input.seasonId,
    });

    try {
      const season = await this.seasonRepository.findById(input.seasonId);
      if (!season || season.leagueId !== input.leagueId) {
        return Result.err({
          code: 'SEASON_NOT_FOUND',
          details: { message: 'Season not found for league' },
        });
      }

      const updatedSeason = season.withSchedulePublished(true);
      await this.seasonRepository.update(updatedSeason);

      const result: PublishLeagueSeasonScheduleResult = {
        success: true,
        seasonId: season.id,
        published: true,
      };
      return Result.ok(result);
    } catch (err) {
      const error = err instanceof Error ? err : new Error('Unknown error');
      this.logger.error('Failed to publish league season schedule', error, {
        leagueId: input.leagueId,
        seasonId: input.seasonId,
      });

      return Result.err({
        code: 'REPOSITORY_ERROR',
        details: { message: error.message },
      });
    }
  }
}