/**
 * Use Case: GetDriverLiveriesUseCase
 *
 * Retrieves all liveries for a specific driver.
 */

import { UseCase } from '@core/shared/application/UseCase';
import type { Logger } from '@core/shared/domain/Logger';
import { Result } from '@core/shared/domain/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { DriverLivery } from '../../domain/entities/DriverLivery';
import { LiveryRepository } from '../../domain/repositories/LiveryRepository';

export interface GetDriverLiveriesInput {
  driverId: string;
}

export type GetDriverLiveriesOutput = DriverLivery[];

export type GetDriverLiveriesErrorCode = 'REPOSITORY_ERROR';

export class GetDriverLiveriesUseCase implements UseCase<GetDriverLiveriesInput, GetDriverLiveriesOutput, GetDriverLiveriesErrorCode> {
  constructor(
    private readonly liveryRepository: LiveryRepository,
    private readonly logger: Logger,
  ) {}

  async execute(input: GetDriverLiveriesInput): Promise<Result<GetDriverLiveriesOutput, ApplicationErrorCode<GetDriverLiveriesErrorCode, { message: string }>>> {
    this.logger.debug(`[GetDriverLiveriesUseCase] Fetching liveries for driver: ${input.driverId}`);

    try {
      const liveries = await this.liveryRepository.findDriverLiveriesByDriverId(input.driverId);
      this.logger.info(`[GetDriverLiveriesUseCase] Found ${liveries.length} liveries for driver: ${input.driverId}`);
      return Result.ok(liveries);
    } catch (error) {
      const err = error instanceof Error ? error : new Error(String(error));
      this.logger.error(`[GetDriverLiveriesUseCase] Error fetching liveries for driver ${input.driverId}:`, err);
      return Result.err({
        code: 'REPOSITORY_ERROR',
        details: { message: err.message },
      });
    }
  }
}