import type { IDriverRepository } from '../../domain/repositories/IDriverRepository';
import { Driver } from '../../domain/entities/Driver';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { UseCase, UseCaseOutputPort } from '@core/shared/application';
import type { Logger } from '@core/shared/application/Logger';

export interface CompleteDriverOnboardingInput {
  userId: string;
  firstName: string;
  lastName: string;
  displayName: string;
  country: string;
  bio?: string;
}

export type CompleteDriverOnboardingResult = {
  driver: Driver;
};

export type CompleteDriverOnboardingErrorCode =
  | 'DRIVER_ALREADY_EXISTS'
  | 'REPOSITORY_ERROR';

export type CompleteDriverOnboardingApplicationError = ApplicationErrorCode<
  CompleteDriverOnboardingErrorCode,
  { message: string }
>;

/**
 * Use Case for completing driver onboarding.
 */
export class CompleteDriverOnboardingUseCase implements UseCase<CompleteDriverOnboardingInput, void, CompleteDriverOnboardingErrorCode> {
  constructor(
    private readonly driverRepository: IDriverRepository,
    private readonly logger: Logger,
    private readonly output: UseCaseOutputPort<CompleteDriverOnboardingResult>,
  ) {}

  async execute(
    input: CompleteDriverOnboardingInput,
  ): Promise<Result<void, CompleteDriverOnboardingApplicationError>> {
    try {
      const existing = await this.driverRepository.findById(input.userId);
      if (existing) {
        return Result.err({
          code: 'DRIVER_ALREADY_EXISTS',
          details: { message: 'Driver already exists' },
        });
      }

      const driver = Driver.create({
        id: input.userId,
        iracingId: input.userId,
        name: input.displayName,
        country: input.country,
        ...(input.bio !== undefined ? { bio: input.bio } : {}),
      });

      await this.driverRepository.create(driver);

      const result: CompleteDriverOnboardingResult = { driver };
      this.output.present(result);
      return Result.ok(void 0);
    } catch (error) {
      const err = error instanceof Error ? error : new Error('Unknown error');

      this.logger.error('CompleteDriverOnboardingUseCase.execute failed', err, {
        input,
      });

      return Result.err({
        code: 'REPOSITORY_ERROR',
        details: {
          message: err.message ?? 'Unexpected repository error',
        },
      });
    }
  }
}