import { Result } from '@core/shared/domain/Result';
import type { MediaStoragePort } from '../ports/MediaStoragePort';

export type GetUploadedMediaInput = {
  storageKey: string;
};

export type GetUploadedMediaResult = {
  bytes: Buffer;
  contentType: string;
};

export class GetUploadedMediaUseCase {
  constructor(private readonly mediaStorage: MediaStoragePort) {}

  async execute(input: GetUploadedMediaInput): Promise<Result<GetUploadedMediaResult | null>> {
    try {
      const bytes = await this.mediaStorage.getBytes!(input.storageKey);
      if (!bytes) {
        return Result.ok(null);
      }

      const metadata = await this.mediaStorage.getMetadata!(input.storageKey);
      const contentType = metadata?.contentType || 'application/octet-stream';

      return Result.ok({
        bytes: Buffer.from(bytes),
        contentType,
      });
    } catch (error) {
      return Result.err(error instanceof Error ? error : new Error(String(error)));
    }
  }
}
