import type { StorageProvider } from './types'
import {
  minio,
  BUCKET_NAME,
  getPresignedUrl,
  deleteObject as minioDeleteObject,
  ensureBucket,
} from '@/lib/minio'

/**
 * S3/MinIO Storage Provider
 *
 * Uses the existing MinIO client for S3-compatible storage.
 * Pre-signed URLs use MINIO_PUBLIC_ENDPOINT for browser access.
 */
export class S3StorageProvider implements StorageProvider {
  private bucket: string

  constructor(bucket?: string) {
    this.bucket = bucket || BUCKET_NAME
  }

  async getUploadUrl(
    key: string,
    contentType: string,
    expirySeconds: number = 900
  ): Promise<string> {
    await ensureBucket(this.bucket)
    return getPresignedUrl(this.bucket, key, 'PUT', expirySeconds)
  }

  async getDownloadUrl(key: string, expirySeconds: number = 900): Promise<string> {
    return getPresignedUrl(this.bucket, key, 'GET', expirySeconds)
  }

  async deleteObject(key: string): Promise<void> {
    await minioDeleteObject(this.bucket, key)
  }

  async putObject(key: string, data: Buffer, contentType: string): Promise<void> {
    await ensureBucket(this.bucket)
    await minio.putObject(this.bucket, key, data, data.length, {
      'Content-Type': contentType,
    })
  }

  async getObject(key: string): Promise<Buffer> {
    const stream = await minio.getObject(this.bucket, key)
    const chunks: Buffer[] = []
    for await (const chunk of stream) {
      chunks.push(chunk as Buffer)
    }
    return Buffer.concat(chunks)
  }

  async objectExists(key: string): Promise<boolean> {
    try {
      await minio.statObject(this.bucket, key)
      return true
    } catch {
      return false
    }
  }
}
