import type { Logger } from '@core/shared/domain/Logger';
import { Result } from '@core/shared/domain/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { Driver } from '../../domain/entities/Driver';
import type { Team } from '../../domain/entities/Team';
import { DriverRepository } from '../../domain/repositories/DriverRepository';
import { TeamMembershipRepository } from '../../domain/repositories/TeamMembershipRepository';
import { TeamRepository } from '../../domain/repositories/TeamRepository';
import type { TeamMembership } from '../../domain/types/TeamMembership';

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: TeamMembershipRepository,
    private readonly driverRepository: DriverRepository,
    private readonly teamRepository: TeamRepository,
    private readonly logger: Logger) {}

  async execute(
    input: GetTeamMembersInput,
  ): Promise<Result<GetTeamMembersResult, 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 });
      }

      return Result.ok({
        team,
        members,
      });
    } 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' },
      });
    }
  }
}
