/**
 * Use Case: UpdateAvatarUseCase
 *
 * Handles the business logic for updating a driver's avatar.
 */

import type { Logger } from '@core/shared/domain/Logger';
import { Result } from '@core/shared/domain/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { v4 as uuidv4 } from 'uuid';
import { Avatar } from '../../domain/entities/Avatar';
import { AvatarRepository } from '../../domain/repositories/AvatarRepository';
import { AvatarId } from '../../domain/value-objects/AvatarId';

export interface UpdateAvatarInput {
  driverId: string;
  mediaUrl: string;
}

export interface UpdateAvatarResult {
  avatarId: string;
  driverId: string;
}

export type UpdateAvatarErrorCode = 'REPOSITORY_ERROR';

export type UpdateAvatarApplicationError = ApplicationErrorCode<
  UpdateAvatarErrorCode,
  { message: string }
>;

export class UpdateAvatarUseCase {
  constructor(
    private readonly avatarRepo: AvatarRepository,
    private readonly logger: Logger,
  ) {}

  async execute(input: UpdateAvatarInput): Promise<Result<UpdateAvatarResult, UpdateAvatarApplicationError>> {
    this.logger.info('[UpdateAvatarUseCase] Updating avatar', {
      driverId: input.driverId,
      mediaUrl: input.mediaUrl,
    });

    try {
      const currentAvatar = await this.avatarRepo.findActiveByDriverId(input.driverId);
      if (currentAvatar) {
        currentAvatar.deactivate();
        await this.avatarRepo.save(currentAvatar);
      }

      const avatarId = AvatarId.create(uuidv4());
      const newAvatar = Avatar.create({
        id: avatarId.toString(),
        driverId: input.driverId,
        mediaUrl: input.mediaUrl,
      });

      await this.avatarRepo.save(newAvatar);

      this.logger.info('[UpdateAvatarUseCase] Avatar updated successfully', {
        driverId: input.driverId,
        avatarId: avatarId.toString(),
      });

      return Result.ok({
        avatarId: avatarId.toString(),
        driverId: input.driverId,
      });
    } catch (error) {
      const err = error instanceof Error ? error : new Error(String(error));

      this.logger.error('[UpdateAvatarUseCase] Error updating avatar', err, {
        driverId: input.driverId,
      });

      return Result.err<UpdateAvatarResult, UpdateAvatarApplicationError>({
        code: 'REPOSITORY_ERROR',
        details: { message: err.message ?? 'Internal error occurred while updating avatar' },
      });
    }
  }
}