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 UnpublishLeagueSeasonScheduleInput = {
  leagueId: string;
  seasonId: string;
};

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

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

export class UnpublishLeagueSeasonScheduleUseCase {
  constructor(
    private readonly seasonRepository: ISeasonRepository,
    private readonly logger: Logger,
    private readonly output: UseCaseOutputPort<UnpublishLeagueSeasonScheduleResult>,
  ) {}

  async execute(
    input: UnpublishLeagueSeasonScheduleInput,
  ): Promise<
    Result<
      void,
      ApplicationErrorCode<UnpublishLeagueSeasonScheduleErrorCode, { message: string }>
    >
  > {
    this.logger.debug('Unpublishing 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(false));

      const result: UnpublishLeagueSeasonScheduleResult = {
        success: true,
        seasonId: season.id,
        published: false,
      };
      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 unpublish league season schedule', error, {
        leagueId: input.leagueId,
        seasonId: input.seasonId,
      });

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