import { Injectable, OnModuleInit } from '@nestjs/common';
import * as fs from 'fs';
import * as path from 'path';
import { exec } from 'child_process';

@Injectable()
export class StorageService implements OnModuleInit {
  // Mendukung UNC Path Windows (\\Server\Share) atau Mount Linux (/mnt/smb)
  private basePath = process.env.SMB_BASE_PATH || path.join(process.cwd(), 'smb-storage-mock');

  constructor() {
    // Buat folder mock jika belum ada (untuk testing lokal sebelum konek ke SMB)
    if (!this.basePath.startsWith('\\\\') && !fs.existsSync(this.basePath)) {
      fs.mkdirSync(this.basePath, { recursive: true });
    }
  }

  async onModuleInit() {
    const user = process.env.SMB_USERNAME;
    const pass = process.env.SMB_PASSWORD;
    const domain = process.env.SMB_DOMAIN ? `${process.env.SMB_DOMAIN}\\` : '';

    if (this.basePath.startsWith('\\\\') && user && pass) {
      console.log(`Connecting to SMB Share: ${this.basePath} as ${domain}${user}...`);
      exec(`net use "${this.basePath}" /user:${domain}${user} "${pass}"`, (err, stdout, stderr) => {
        if (err) {
          console.error("Gagal melakukan autentikasi ke server SMB:", stderr || err.message);
        } else {
          console.log("Berhasil terhubung ke server SMB:", stdout);
        }
      });
    }
  }

  // Frontend tidak perlu merubah cara kerja, kita beri URL ke endpoint Controller kita sendiri
  async getPresignedUploadUrl(objectName: string): Promise<string> {
    const backendUrl = process.env.BACKEND_URL || 'http://localhost:3000';
    return `${backendUrl}/storage/upload/${encodeURIComponent(objectName)}`;
  }

  async getPresignedDownloadUrl(objectName: string): Promise<string> {
    const backendUrl = process.env.BACKEND_URL || 'http://localhost:3000';
    return `${backendUrl}/storage/download/${encodeURIComponent(objectName)}`;
  }

  getFilePath(objectName: string): string {
    return path.join(this.basePath, objectName);
  }
}
