import {
  StorageDriver,
  LocalStorageConfig,
  StorageOption,
} from '../interfaces';
import { dirname, join, resolve, sep } from 'path';
import * as fs from 'fs-extra';
import { Readable } from 'stream';
import { randomUUID } from 'node:crypto';
import { createReadStream, createWriteStream } from 'node:fs';
import { pipeline } from 'node:stream/promises';

export class LocalDriver implements StorageDriver {
  private readonly config: LocalStorageConfig;

  constructor(config: LocalStorageConfig) {
    this.config = config;
  }

  private _fullPath(filePath: string): string {
    const storageRoot = resolve(this.config.storagePath);
    const fullPath = resolve(storageRoot, filePath);
    if (fullPath !== storageRoot && !fullPath.startsWith(storageRoot + sep)) {
      throw new Error('Invalid file path');
    }
    return fullPath;
  }

  // Goes through a temp file so a failed stream never touches the file at fullPath
  private async _writeStream(fullPath: string, file: Readable): Promise<void> {
    // _fullPath accepts the root itself, whose parent is outside the storage
    if (fullPath === resolve(this.config.storagePath)) {
      throw new Error('Invalid file path');
    }

    const parentDir = dirname(fullPath);
    // a name of its own, as the target's can already be at the file system limit
    const tempPath = join(parentDir, `.${randomUUID()}.tmp`);
    await fs.mkdir(parentDir, { recursive: true });

    try {
      await pipeline(file, createWriteStream(tempPath));
      await fs.rename(tempPath, fullPath);
    } catch (err) {
      await fs.remove(tempPath).catch(() => undefined);
      await this._removeEmptyDir(parentDir);
      throw err;
    }
  }

  private async _removeEmptyDir(dir: string): Promise<void> {
    if (dir !== resolve(this.config.storagePath)) {
      // rmdir refuses non-empty directories, so errors are ignored
      await fs.rmdir(dir).catch(() => undefined);
    }
  }

  async upload(filePath: string, file: Buffer | Readable): Promise<void> {
    try {
      const fullPath = this._fullPath(filePath);
      if (Buffer.isBuffer(file)) {
        await fs.outputFile(fullPath, file);
      } else {
        await this._writeStream(fullPath, file);
      }
    } catch (err) {
      throw new Error(`Failed to upload file: ${(err as Error).message}`);
    }
  }

  async uploadStream(filePath: string, file: Readable, options?: { recreateClient?: boolean }): Promise<void> {
    try {
      await this._writeStream(this._fullPath(filePath), file);
    } catch (err) {
      throw new Error(`Failed to upload file: ${(err as Error).message}`);
    }
  }

  async copy(fromFilePath: string, toFilePath: string): Promise<void> {
    try {
      const fromFullPath = this._fullPath(fromFilePath);
      const toFullPath = this._fullPath(toFilePath);

      if (await this.exists(fromFilePath)) {
        await fs.copy(fromFullPath, toFullPath);
      }
    } catch (err) {
      throw new Error(`Failed to copy file: ${(err as Error).message}`);
    }
  }

  async read(filePath: string): Promise<Buffer> {
    try {
      return await fs.readFile(this._fullPath(filePath));
    } catch (err) {
      throw new Error(`Failed to read file: ${(err as Error).message}`);
    }
  }

  async readStream(filePath: string): Promise<Readable> {
    const fullPath = this._fullPath(filePath);
    if (!(await fs.pathExists(fullPath))) {
      throw new Error(`File not found: ${filePath}`);
    }
    return createReadStream(fullPath);
  }

  async readRangeStream(
    filePath: string,
    range: { start: number; end: number },
  ): Promise<Readable> {
    const fullPath = this._fullPath(filePath);
    if (!(await fs.pathExists(fullPath))) {
      throw new Error(`File not found: ${filePath}`);
    }
    return createReadStream(fullPath, {
      start: range.start,
      end: range.end,
    });
  }

  async exists(filePath: string): Promise<boolean> {
    try {
      return await fs.pathExists(this._fullPath(filePath));
    } catch (err) {
      throw new Error(
        `Failed to check file existence: ${(err as Error).message}`,
      );
    }
  }

  async getSignedUrl(filePath: string, expireIn: number): Promise<string> {
    throw new Error('Signed URLs are not supported for local storage.');
  }

  getUrl(filePath: string): string {
    return this._fullPath(filePath);
  }

  async delete(filePath: string): Promise<void> {
    try {
      const storageRoot = resolve(this.config.storagePath);
      const fullPath = this._fullPath(filePath);
      // _fullPath accepts the root itself, which must never be removed
      if (fullPath === storageRoot) {
        throw new Error('Invalid file path');
      }
      await fs.remove(fullPath);
      await this._removeEmptyDir(dirname(fullPath));
    } catch (err) {
      throw new Error(`Failed to delete file: ${(err as Error).message}`);
    }
  }

  getDriver(): typeof fs {
    return fs;
  }

  getDriverName(): string {
    return StorageOption.LOCAL;
  }

  getConfig(): Record<string, any> {
    return this.config;
  }
}
