import { describe, it, expect, beforeEach } from 'vitest';
import { mkdtempSync, readFileSync, existsSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { MediaStore } from '@main/services/MediaStore.js';

describe('MediaStore', () => {
  let tmp: string;
  let store: MediaStore;

  beforeEach(() => {
    tmp = mkdtempSync(join(tmpdir(), 'inkling-media-'));
    store = new MediaStore(tmp);
  });

  it('saves a png under media/{noteId}/', async () => {
    const bytes = Buffer.from('\x89PNG\r\n\x1a\n' + 'A'.repeat(100));
    const saved = await store.saveImage('note-123', bytes, 'image/png');
    expect(saved.relPath.startsWith('media/note-123/')).toBe(true);
    expect(saved.relPath.endsWith('.png')).toBe(true);
    expect(saved.bytes).toBe(bytes.length);
    expect(readFileSync(join(tmp, saved.relPath)).equals(bytes)).toBe(true);
  });

  it('saves multiple images with unique filenames', async () => {
    const bytes = Buffer.from('abc');
    const a = await store.saveImage('n', bytes, 'image/png');
    const b = await store.saveImage('n', bytes, 'image/png');
    expect(a.relPath).not.toBe(b.relPath);
  });

  it('deleteNoteDirectory removes the note dir', async () => {
    await store.saveImage('note-x', Buffer.from('abc'), 'image/png');
    await store.deleteNoteDirectory('note-x');
    expect(existsSync(join(tmp, 'media/note-x'))).toBe(false);
  });

  it('listNoteDirs returns dir names', async () => {
    await store.saveImage('alpha', Buffer.from('a'), 'image/png');
    await store.saveImage('beta', Buffer.from('b'), 'image/png');
    expect((await store.listNoteDirs()).sort()).toEqual(['alpha', 'beta']);
  });
});
