import type { AsyncUseCase } from '@core/shared/application';
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 { CompleteDriverOnboardingCommand } from '../dto/CompleteDriverOnboardingCommand';

/**
 * Use Case for completing driver onboarding.
 */
export class CompleteDriverOnboardingUseCase
  implements AsyncUseCase<CompleteDriverOnboardingCommand, { driverId: string }, string>
{
  constructor(private readonly driverRepository: IDriverRepository) {}

  async execute(command: CompleteDriverOnboardingCommand): Promise<Result<{ driverId: string }, ApplicationErrorCode<string>>> {
    try {
      // Check if driver already exists
      const existing = await this.driverRepository.findById(command.userId);
      if (existing) {
        return Result.err({ code: 'DRIVER_ALREADY_EXISTS' });
      }

      // Create new driver
      const driver = Driver.create({
        id: command.userId,
        iracingId: command.userId, // Assuming userId is iracingId for now
        name: command.displayName,
        country: command.country,
        ...(command.bio !== undefined ? { bio: command.bio } : {}),
      });

      await this.driverRepository.create(driver);

      return Result.ok({ driverId: driver.id });
    } catch {
      return Result.err({ code: 'UNKNOWN_ERROR' });
    }
  }
}