import { Inject, Logger } from '@nestjs/common';
import { type CommandHandler, type ICommandHandler } from '@nestjs/cqrs';
import { CommandHandler as CqrsCommandHandler } from '@nestjs/cqrs';
import {
  MEDIA_STORAGE_SERVICE,
  type IMediaStorageService,
} from '@modules/listings/infrastructure/services/media-storage.service';
import { GenerateTransferUploadUrlsCommand } from './generate-transfer-upload-urls.command';

export interface TransferUploadUrlResult {
  uploadUrl: string;
  objectKey: string;
  publicUrl: string;
}

@CqrsCommandHandler(GenerateTransferUploadUrlsCommand)
export class GenerateTransferUploadUrlsHandler
  implements ICommandHandler<GenerateTransferUploadUrlsCommand>
{
  private readonly logger = new Logger(GenerateTransferUploadUrlsHandler.name);

  constructor(
    @Inject(MEDIA_STORAGE_SERVICE)
    private readonly storage: IMediaStorageService,
  ) {}

  async execute(command: GenerateTransferUploadUrlsCommand): Promise<TransferUploadUrlResult[]> {
    const folder = command.listingId
      ? `transfer/${command.sellerId}/${command.listingId}`
      : `transfer/${command.sellerId}/draft`;

    const results: TransferUploadUrlResult[] = [];

    for (const file of command.files.slice(0, 10)) {
      try {
        const result = await this.storage.generatePresignedUpload(
          folder,
          file.fileName,
          file.mimeType,
          600, // 10 min expiry
        );
        results.push(result);
      } catch (err) {
        this.logger.error(
          `Failed to generate upload URL for ${file.fileName}: ${err instanceof Error ? err.message : 'Unknown'}`,
        );
      }
    }

    return results;
  }
}
