import type { Logger, UseCaseOutputPort } from '@core/shared/application';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';

import type { ISeasonRepository } from '../../domain/repositories/ISeasonRepository';

export type 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: ISeasonRepository,
    private readonly logger: Logger,
    private readonly output: UseCaseOutputPort<PublishLeagueSeasonScheduleResult>,
  ) {}

  async execute(
    input: PublishLeagueSeasonScheduleInput,
  ): Promise<
    Result<
      void,
      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' },
        });
      }

      await this.seasonRepository.update(season.withSchedulePublished(true));

      const result: PublishLeagueSeasonScheduleResult = {
        success: true,
        seasonId: season.id,
        published: true,
      };
      this.output.present(result);

      return Result.ok(undefined);
    } 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 },
      });
    }
  }
}