import { mkdir, writeFile, rm, readdir } from 'node:fs/promises';
import { join } from 'node:path';
import { v4 as uuidv4 } from 'uuid';

export interface SavedMedia {
  relPath: string;
  mime: string;
  bytes: number;
}

export class MediaStore {
  constructor(private profileDir: string) {}

  async saveImage(noteId: string, bytes: Buffer, mime: string): Promise<SavedMedia> {
    const dir = join(this.profileDir, 'media', noteId);
    await mkdir(dir, { recursive: true });
    const ext = mime === 'image/png' ? 'png' : mime === 'image/jpeg' ? 'jpg' : 'bin';
    const filename = `${uuidv4()}.${ext}`;
    await writeFile(join(dir, filename), bytes);
    return { relPath: `media/${noteId}/${filename}`, mime, bytes: bytes.length };
  }

  async deleteNoteDirectory(noteId: string): Promise<void> {
    await rm(join(this.profileDir, 'media', noteId), { recursive: true, force: true });
  }

  async listNoteDirs(): Promise<string[]> {
    const root = join(this.profileDir, 'media');
    try {
      const entries = await readdir(root, { withFileTypes: true });
      return entries.filter((e) => e.isDirectory()).map((e) => e.name);
    } catch (err) {
      if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];
      throw err;
    }
  }

  absolutePath(relPath: string): string {
    return join(this.profileDir, relPath);
  }
}
