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

export type GetDriverTeamInput = {
  driverId: string;
};

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

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

/**
 * Use Case for retrieving a driver's team.
 * Orchestrates domain logic and returns result.
 */
export class GetDriverTeamUseCase {
  constructor(
    private readonly teamRepository: ITeamRepository,
    private readonly membershipRepository: ITeamMembershipRepository,
    private readonly logger: Logger,
    private readonly output: UseCaseOutputPort<GetDriverTeamResult>,
  ) {}

  async execute(input: GetDriverTeamInput): Promise<Result<void, 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}`);
      this.output.present(result);

      return Result.ok(undefined);
    } 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' } });
    }
  }
}