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

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 {
  constructor(
    private readonly driverRepository: DriverRepository,
    private readonly logger: Logger,
  ) {}

  async execute(
    input: CompleteDriverOnboardingInput,
  ): Promise<
    Result<
      CompleteDriverOnboardingResult,
      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 };
      return Result.ok(result);
    } 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',
        },
      });
    }
  }
}