import { Result } from '@core/shared/domain/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { League } from '../../domain/entities/League';
import type { LeagueMembershipRepository } from '../../domain/repositories/LeagueMembershipRepository';
import type { LeagueRepository } from '../../domain/repositories/LeagueRepository';

export type GetAllLeaguesWithCapacityInput = {};

export type LeagueCapacitySummary = {
  league: League;
  currentDrivers: number;
  maxDrivers: number;
};

export type GetAllLeaguesWithCapacityResult = {
  leagues: LeagueCapacitySummary[];
};

export type GetAllLeaguesWithCapacityErrorCode = 'REPOSITORY_ERROR';

/**
 * Use Case for retrieving all leagues with capacity information.
 * Orchestrates domain logic and delegates presentation to an output port.
 */
export class GetAllLeaguesWithCapacityUseCase {
  constructor(
    private readonly leagueRepository: LeagueRepository,
    private readonly leagueMembershipRepository: LeagueMembershipRepository,
  ) {}

  async execute(
    _input: GetAllLeaguesWithCapacityInput = {},
  ): Promise<
    Result<
      GetAllLeaguesWithCapacityResult,
      ApplicationErrorCode<GetAllLeaguesWithCapacityErrorCode, { message: string }>
    >
  > {
    void _input;
    try {
      const leagues = await this.leagueRepository.findAll();

      const summaries: LeagueCapacitySummary[] = [];

      for (const league of leagues) {
        const members = await this.leagueMembershipRepository.getLeagueMembers(league.id.toString());

        const currentDrivers = members.filter(
          (m) =>
            m.status.toString() === 'active' &&
            (m.role.toString() === 'owner' ||
              m.role.toString() === 'admin' ||
              m.role.toString() === 'steward' ||
              m.role.toString() === 'member'),
        ).length;

        const maxDrivers = league.settings.maxDrivers ?? 0;

        summaries.push({ league, currentDrivers, maxDrivers });
      }

      return Result.ok({ leagues: summaries });
    } catch (error: unknown) {
      const message =
        error instanceof Error && error.message
          ? error.message
          : 'Failed to load leagues with capacity';

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