import { Inject, Injectable, Logger, NotFoundException } from "@nestjs/common";
import { ConfigType } from "@nestjs/config";
import { Client } from "minio";
import { Readable } from "stream";
import { minioConfig } from "./minio.config";

@Injectable()
export class MinioService {
  private readonly client: Client;
  private readonly logger = new Logger(MinioService.name);
  private readonly bucket: string;

  constructor(
    @Inject(minioConfig.KEY)
    private readonly config: ConfigType<typeof minioConfig>,
  ) {
    console.log('[MinioService] Configuration loaded:', {
      endPoint: config.endPoint,
      port: config.port,
      useSSL: config.useSSL,
      accessKey: config.accessKey,
      secretKey: config.secretKey ? '***HIDDEN***' : 'EMPTY',
      bucket: config.bucket,
    });
    this.bucket = config.bucket;
    this.client = new Client({
      endPoint: config.endPoint,
      port: config.port,
      useSSL: config.useSSL,
      accessKey: config.accessKey,
      secretKey: config.secretKey,
    });
  }

  async uploadFile(
    objectName: string,
    buffer: Buffer,
    contentType: string,
  ): Promise<string> {
    try {
      await this.client.putObject(this.bucket, objectName, buffer, buffer.length, {
        "Content-Type": contentType,
      });
      this.logger.log(`File uploaded successfully: ${objectName}`);
      return this.getPublicUrl(objectName);
    } catch (error) {
      this.logger.error(`Failed to upload file ${objectName}:`, error);
      throw error;
    }
  }

  getPublicUrl(objectName: string): string {
    const protocol = this.config.useSSL ? "https" : "http";
    return `${protocol}://${this.config.endPoint}:${this.config.port}/${this.bucket}/${objectName}`;
  }

  getObjectNameFromUrl(value: string): string {
    const trimmed = value.trim();
    if (!trimmed) {
      throw new NotFoundException("File object path is empty");
    }

    if (!/^https?:\/\//i.test(trimmed)) {
      return trimmed.replace(/^\/+/, "");
    }

    const url = new URL(trimmed);
    const parts = url.pathname.split("/").filter(Boolean);
    if (parts[0] === this.bucket) {
      parts.shift();
    }

    const objectName = parts.join("/");
    if (!objectName) {
      throw new NotFoundException("File object path is empty");
    }

    return objectName;
  }

  async deleteFile(objectName: string): Promise<void> {
    try {
      await this.client.removeObject(this.bucket, objectName);
      this.logger.log(`File deleted successfully: ${objectName}`);
    } catch (error) {
      this.logger.error(`Failed to delete file ${objectName}:`, error);
      throw error;
    }
  }

  async getFileStream(objectName: string): Promise<Readable> {
    try {
      return this.client.getObject(this.bucket, objectName);
    } catch (error) {
      this.logger.error(`Failed to get file ${objectName}:`, error);
      throw error;
    }
  }

  async getSignedUrl(objectName: string, expirySeconds: number = 300): Promise<string> {
    try {
      return await this.client.presignedGetObject(this.bucket, objectName, expirySeconds);
    } catch (error) {
      this.logger.error(`Failed to generate signed URL for ${objectName}:`, error);
      throw error;
    }
  }
}
