import type { ITeamRepository } from '../../domain/repositories/ITeamRepository';
import type { ITeamMembershipRepository } from '../../domain/repositories/ITeamMembershipRepository';
import type { DriverTeamResultDTO } from '../presenters/IDriverTeamPresenter';
import type { AsyncUseCase, Logger } from '@core/shared/application';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';

/**
 * Use Case for retrieving a driver's team.
 * Orchestrates domain logic and returns result.
 */
export class GetDriverTeamUseCase
  implements AsyncUseCase<{ driverId: string }, Result<DriverTeamResultDTO, ApplicationErrorCode<'MEMBERSHIP_NOT_FOUND' | 'TEAM_NOT_FOUND' | 'REPOSITORY_ERROR', { message: string }>>>
{
  constructor(
    private readonly teamRepository: ITeamRepository,
    private readonly membershipRepository: ITeamMembershipRepository,
    private readonly logger: Logger,
  ) {}

  async execute(input: { driverId: string }): Promise<Result<DriverTeamResultDTO, ApplicationErrorCode<'MEMBERSHIP_NOT_FOUND' | 'TEAM_NOT_FOUND' | 'REPOSITORY_ERROR', { message: string }>>> {
    this.logger.debug(`Executing GetDriverTeamUseCase for driverId: ${input.driverId}`);
    try {
      const membership = await this.membershipRepository.getActiveMembershipForDriver(input.driverId);
      if (!membership) {
        this.logger.warn(`No active membership found for driverId: ${input.driverId}`);
        return Result.err({ code: 'MEMBERSHIP_NOT_FOUND', details: { message: `No active membership found for driver ${input.driverId}` } });
      }
      this.logger.debug(`Found membership for driverId: ${input.driverId}, teamId: ${membership.teamId}`);

      const team = await this.teamRepository.findById(membership.teamId);
      if (!team) {
        this.logger.error(`Team not found for teamId: ${membership.teamId}`);
        return Result.err({ code: 'TEAM_NOT_FOUND', details: { message: `Team not found for teamId ${membership.teamId}` } });
      }
      this.logger.debug(`Found team for teamId: ${team.id}, name: ${team.name}`);

      const dto: DriverTeamResultDTO = {
        team,
        membership,
        driverId: input.driverId,
      };

      this.logger.info(`Successfully retrieved driver team for driverId: ${input.driverId}`);
      return Result.ok(dto);
    } catch (error) {
      this.logger.error('Error executing GetDriverTeamUseCase', error instanceof Error ? error : new Error(String(error)));
      return Result.err({ code: 'REPOSITORY_ERROR', details: { message: error instanceof Error ? error.message : 'Unknown error occurred' } });
    }
  }
}