import { Injectable, Logger, Inject } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as Minio from 'minio';

export interface MinioConfig {
  endpoint: string;
  port: number;
  accessKey: string;
  secretKey: string;
  useSSL: boolean;
  region: string;
  bucketDocuments: string;
  bucketArchives: string;
}

@Injectable()
export class StorageService {
  private readonly logger = new Logger(StorageService.name);
  private client: Minio.Client | null = null;

  constructor(@Inject(ConfigService) private configService: ConfigService) {}

  async initialize(): Promise<void> {
    try {
      const config = this.configService.get<MinioConfig>('minio');

      if (!config) {
        throw new Error('MinIO configuration not found');
      }

      this.client = new Minio.Client({
        endPoint: config.endpoint,
        port: config.port,
        useSSL: config.useSSL,
        accessKey: config.accessKey,
        secretKey: config.secretKey,
        region: config.region,
      });

      await this.ensureBuckets(config);
      this.logger.log('MinIO storage service initialized successfully');
    } catch (error) {
      this.logger.error('Failed to initialize storage service', error);
      throw error;
    }
  }

  private async ensureBuckets(config: MinioConfig): Promise<void> {
    const buckets = [config.bucketDocuments, config.bucketArchives];

    for (const bucket of buckets) {
      try {
        const exists = await this.client!.bucketExists(bucket);
        if (!exists) {
          await this.client!.makeBucket(bucket, config.region);
          this.logger.log(`Created bucket: ${bucket}`);
        }
      } catch (error) {
        this.logger.warn(`Bucket operation failed for ${bucket}`, error);
      }
    }
  }

  getClient(): Minio.Client {
    if (!this.client) {
      throw new Error('Storage client not initialized');
    }
    return this.client;
  }
}
