import type { ITeamMembershipRepository } from '../../domain/repositories/ITeamMembershipRepository';
import type { IDriverRepository } from '../../domain/repositories/IDriverRepository';
import type { ITeamRepository } from '../../domain/repositories/ITeamRepository';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { Logger } from '@core/shared/application';
import type { UseCaseOutputPort } from '@core/shared/application/UseCaseOutputPort';
import type { TeamMembership } from '../../domain/types/TeamMembership';
import type { Team } from '../../domain/entities/Team';
import type { Driver } from '../../domain/entities/Driver';

export type GetTeamMembersInput = {
  teamId: string;
};

export type TeamMemberDetail = {
  membership: TeamMembership;
  driver: Driver | null;
};

export type GetTeamMembersResult = {
  team: Team;
  members: TeamMemberDetail[];
};

export type GetTeamMembersErrorCode = 'TEAM_NOT_FOUND' | 'REPOSITORY_ERROR';

/**
 * Use Case for retrieving team members.
 */
export class GetTeamMembersUseCase {
  constructor(
    private readonly membershipRepository: ITeamMembershipRepository,
    private readonly driverRepository: IDriverRepository,
    private readonly teamRepository: ITeamRepository,
    private readonly logger: Logger,
    private readonly output: UseCaseOutputPort<GetTeamMembersResult>,
  ) {}

  async execute(
    input: GetTeamMembersInput,
  ): Promise<Result<void, ApplicationErrorCode<GetTeamMembersErrorCode, { message: string }>>> {
    this.logger.debug(`Executing GetTeamMembersUseCase for teamId: ${input.teamId}`);

    try {
      const team = await this.teamRepository.findById(input.teamId);

      if (!team) {
        return Result.err({
          code: 'TEAM_NOT_FOUND',
          details: { message: 'Team not found' },
        });
      }

      const memberships = await this.membershipRepository.getTeamMembers(input.teamId);
      this.logger.info(`Found ${memberships.length} memberships for teamId: ${input.teamId}`);

      const members: TeamMemberDetail[] = [];

      for (const membership of memberships) {
        this.logger.debug(`Processing membership for driverId: ${membership.driverId}`);
        const driver = await this.driverRepository.findById(membership.driverId);

        if (!driver) {
          this.logger.warn(
            `Driver with ID ${membership.driverId} not found while fetching team members for team ${input.teamId}.`,
          );
          members.push({ membership, driver: null });
          continue;
        }

        members.push({ membership, driver });
      }

      this.output.present({
        team,
        members,
      });

      return Result.ok(undefined);
    } catch (err) {
      const error = err as { message?: string } | undefined;

      this.logger.error(
        `Error in GetTeamMembersUseCase for teamId: ${input.teamId}`,
        err as Error,
        { teamId: input.teamId },
      );

      return Result.err({
        code: 'REPOSITORY_ERROR',
        details: { message: error?.message ?? 'Failed to load team members' },
      });
    }
  }
}
