import { PutObjectCommand, S3Client } from '@aws-sdk/client-s3';
import { Injectable, Logger } from '@nestjs/common';
import { type IPdfStorageService } from '../../domain/services/pdf-storage.service';

@Injectable()
export class MinioPdfStorageService implements IPdfStorageService {
  private readonly logger = new Logger(MinioPdfStorageService.name);
  private readonly s3: S3Client;
  private readonly bucket: string;
  private readonly publicBaseUrl: string;

  constructor() {
    const endpoint = process.env['MINIO_ENDPOINT'] || 'localhost';
    const port = parseInt(process.env['MINIO_PORT'] || '9000', 10);
    const useSSL = process.env['MINIO_USE_SSL'] === 'true';
    const protocol = useSSL ? 'https' : 'http';

    this.bucket = process.env['MINIO_BUCKET'] || 'goodgo-media';
    this.publicBaseUrl = `${protocol}://${endpoint}:${port}/${this.bucket}`;

    this.s3 = new S3Client({
      endpoint: `${protocol}://${endpoint}:${port}`,
      region: 'us-east-1',
      credentials: {
        accessKeyId: process.env['MINIO_ACCESS_KEY'] || '',
        secretAccessKey: process.env['MINIO_SECRET_KEY'] || '',
      },
      forcePathStyle: true,
    });
  }

  async uploadPdf(buffer: Buffer, reportId: string): Promise<string> {
    const objectKey = `reports/${reportId}.pdf`;

    await this.s3.send(
      new PutObjectCommand({
        Bucket: this.bucket,
        Key: objectKey,
        Body: buffer,
        ContentType: 'application/pdf',
        ContentDisposition: `inline; filename="report-${reportId}.pdf"`,
      }),
    );

    const url = `${this.publicBaseUrl}/${objectKey}`;
    this.logger.log(`PDF uploaded: ${url}`);
    return url;
  }
}
