import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { createStore } from '../src/store.js';
import { validateImage } from '../src/image.js';
import { encodePng } from '../src/png.js';

test('stores memes in dated hash shards and paginates', async () => {
  const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'meme-protocol-'));
  const store = await createStore({ dataDir: dir });
  const buffer = encodePng(16, 16, () => [0, 255, 65, 255]);
  const image = validateImage(buffer, {
    maxBytes: 5 * 1024 * 1024,
    maxWidth: 6000,
    maxHeight: 6000,
    maxPixels: 20_000_000
  });
  const meme = await store.save({
    buffer,
    image,
    originalName: 'test.png',
    createdAt: '2026-05-08T12:00:00.000Z'
  });

  assert.equal(store.count(), 1);
  assert.equal(store.list({ page: 1, pageSize: 12 }).memes[0].id, meme.id);
  assert.equal(store.list({ page: 1, pageSize: 12 }).memes[0].viewCount, 0);
  assert.match(store.get(meme.id).storageKey, /^memes\/2026\/05\/08\/[a-f0-9]{2}\/[a-f0-9]{2}\//);
  await fs.access(path.join(dir, store.get(meme.id).storageKey));
});

test('increments view and download counters', async () => {
  const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'meme-protocol-'));
  const store = await createStore({ dataDir: dir });
  const buffer = encodePng(16, 16, () => [0, 255, 65, 255]);
  const image = validateImage(buffer, {
    maxBytes: 5 * 1024 * 1024,
    maxWidth: 6000,
    maxHeight: 6000,
    maxPixels: 20_000_000
  });
  const meme = await store.save({
    buffer,
    image,
    originalName: 'test.png',
    createdAt: '2026-05-08T12:00:00.000Z'
  });

  await store.incrementMetric(meme.id, 'viewCount');
  await store.incrementMetric(meme.id, 'downloadCount');

  const listed = store.list({ page: 1, pageSize: 12 }).memes[0];
  assert.equal(listed.viewCount, 1);
  assert.equal(listed.downloadCount, 1);
});
