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 { Team } from '../../domain/entities/Team';
import { TeamMembershipRepository } from '../../domain/repositories/TeamMembershipRepository';
import { TeamRepository } from '../../domain/repositories/TeamRepository';
import { TeamMembership } from '../../domain/types/TeamMembership';

export interface GetDriverTeamInput {
  driverId: string;
}

export type GetDriverTeamErrorCode = 'MEMBERSHIP_NOT_FOUND' | 'TEAM_NOT_FOUND' | 'REPOSITORY_ERROR';

export interface GetDriverTeamResult {
  driverId: string;
  team: Team;
  membership: TeamMembership;
}

export class GetDriverTeamUseCase {
  constructor(
    private readonly teamRepository: TeamRepository,
    private readonly membershipRepository: TeamMembershipRepository,
    private readonly logger: Logger,
  ) {}

  async execute(
    input: GetDriverTeamInput,
  ): Promise<Result<GetDriverTeamResult, ApplicationErrorCode<GetDriverTeamErrorCode, { 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}`);

      const result: GetDriverTeamResult = {
        driverId: input.driverId,
        team,
        membership,
      };

      this.logger.info(`Successfully retrieved driver team for driverId: ${input.driverId}`);
      return Result.ok(result);
    } catch (error: unknown) {
      this.logger.error(`Error getting driver team: ${error instanceof Error ? error.message : 'Unknown error'}`);
      return Result.err({
        code: 'REPOSITORY_ERROR',
        details: { message: error instanceof Error ? error.message : 'Unknown error' },
      });
    }
  }
}