import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { randomUUID } from 'node:crypto';
import { createReadStream } from 'node:fs';
import { mkdir, readFile, unlink, writeFile } from 'node:fs/promises';
import { dirname, join, resolve, sep } from 'node:path';

const EXT_BY_MIME: Record<string, string> = {
  'image/jpeg': 'jpg',
  'image/png': 'png',
  'image/webp': 'webp',
  'image/heic': 'heic',
  'application/pdf': 'pdf',
};

/**
 * Private file storage on the local filesystem. Keys are opaque (random UUID +
 * derived extension), sharded into subdirs, and never derived from user input —
 * so paths are unguessable and unenumerable. Swappable for S3 later behind the
 * same tiny surface (save/stream/remove). Nothing is written under a public dir.
 */
@Injectable()
export class StorageService {
  private readonly root: string;

  constructor(config: ConfigService) {
    // Files live under <STORAGE_LOCAL_ROOT>/uploads (STORAGE_LOCAL_ROOT is the
    // documented env var; defaults to ./storage next to the running process).
    const base = config.get<string>('STORAGE_LOCAL_ROOT') ?? join(process.cwd(), 'storage');
    this.root = resolve(base, 'uploads');
  }

  extForMime(mime: string): string | undefined {
    return EXT_BY_MIME[mime];
  }

  /** Persist a buffer under a fresh opaque key; returns the relative key. */
  async save(buffer: Buffer, ext: string): Promise<string> {
    const id = randomUUID();
    const key = `${id.slice(0, 2)}/${id}.${ext}`;
    const abs = this.absolute(key);
    await mkdir(dirname(abs), { recursive: true });
    await writeFile(abs, buffer);
    return key;
  }

  /** Resolve a key to an absolute path, refusing anything that escapes the root. */
  absolute(key: string): string {
    const abs = resolve(this.root, key);
    if (abs !== this.root && !abs.startsWith(this.root + sep)) {
      throw new Error('Invalid storage key');
    }
    return abs;
  }

  stream(key: string) {
    return createReadStream(this.absolute(key));
  }

  /** Whole file in memory — for inlining an image into a document being rendered. */
  read(key: string): Promise<Buffer> {
    return readFile(this.absolute(key));
  }

  async remove(key: string): Promise<void> {
    try {
      await unlink(this.absolute(key));
    } catch {
      // already gone — nothing to do
    }
  }
}
