import { Injectable, NotFoundException } from '@nestjs/common';
import { ObjectStorageService as GCSService } from '../../lib/objectStorage';

const svc = new GCSService();

@Injectable()
export class ObjectStorageService {
  /**
   * Generate a presigned PUT URL for direct-to-GCS upload.
   * Returns { uploadUrl, objectPath } where objectPath is what you store in DB.
   */
  async getUploadUrl(): Promise<{ uploadUrl: string; objectPath: string }> {
    const uploadUrl = await svc.getObjectEntityUploadURL();
    const objectPath = svc.normalizeObjectEntityPath(uploadUrl.split('?')[0]);
    return { uploadUrl, objectPath };
  }

  /**
   * Stream a GCS object for download/serving.
   * objectPath must start with /objects/
   */
  async streamObject(objectPath: string): Promise<{ stream: NodeJS.ReadableStream; contentType: string; size?: string }> {
    try {
      const file = await svc.getObjectEntityFile(objectPath);
      const [metadata] = await file.getMetadata();
      const stream = file.createReadStream();
      return {
        stream,
        contentType: (metadata.contentType as string) || 'application/octet-stream',
        size: metadata.size ? String(metadata.size) : undefined,
      };
    } catch {
      throw new NotFoundException('File not found');
    }
  }

  /**
   * Normalize a raw GCS URL to an objectPath for DB storage.
   */
  normalize(rawPath: string): string {
    return svc.normalizeObjectEntityPath(rawPath);
  }
}
