import { Injectable } from '@nestjs/common';
import * as fs from 'fs';
import path, { dirname } from 'path';
import {IStorageDriver} from "../interface/storage.interface"


interface FilesystemConfig {
  basePath: string;
  baseUrl: string;
}


export class FileSystemDriver implements IStorageDriver {
  constructor(private config: FilesystemConfig) {}

  /*
  ===============================
  Upload
  ===============================
  */
  async upload(file: Buffer, filePath: string): Promise<string> {
    console.log(this.config , "config");
    const fullPath = path.join(this.config.basePath, filePath);
    await fs.promises.mkdir(dirname(fullPath), { recursive: true });
    await fs.promises.writeFile(fullPath, file);

    return filePath;
  }

  /*
  ===============================
  Delete
  ===============================
  */
  async delete(): Promise<void> {
    // const fullPath = path.join(this.config.basePath, filePath);

    // if (!fs.existsSync(fullPath)) return;

    // await fs.promises.unlink(fullPath);

    // await this.cleanupEmptyDirs(dirname(fullPath));
  }

  /*
  ===============================
  URL
  ===============================
  */
  getUrl(filePath: string): string {
    return `${this.config.baseUrl}/${filePath}`;
  }

  /*
  ===============================
  Cleanup empty folders
  ===============================
  */
  private async cleanupEmptyDirs(dir: string) {
    if (!dir.startsWith(this.config.basePath)) return;

    const files = await fs.promises.readdir(dir);
    if (files.length > 0) return;

    await fs.promises.rmdir(dir);

    const parent = dirname(dir);
    if (parent !== this.config.basePath) {
      await this.cleanupEmptyDirs(parent);
    }
  }


   async getAvailableImages(): Promise<{ Key?: string }[]> {
    const images: { Key?: string }[] = [];
 return images;
  }
}

