import { beforeEach, describe, expect, it } from 'vitest';
import { createFontAsset, type FontAsset } from '@core/font-asset';
import { useFontStore } from './FontStore';

const asset = (family: string, id = 1): FontAsset =>
  createFontAsset({
    family,
    data: new Uint8Array(8).buffer,
    format: 'woff2',
    fileName: `${family}.woff2`,
    id,
  });

beforeEach(() => useFontStore.getState().reset());

describe('FontStore', () => {
  it('add assigns the next free id (one past the max)', () => {
    const a = useFontStore.getState().add(asset('A'));
    const b = useFontStore.getState().add(asset('B'));
    expect(a.id).toBe(1);
    expect(b.id).toBe(2);
    expect(useFontStore.getState().fonts.map((f) => f.family)).toEqual(['A', 'B']);
  });

  it('addFonts reassigns ids and appends without clobbering', () => {
    useFontStore.getState().add(asset('Existing'));
    useFontStore.getState().addFonts([asset('X', 1), asset('Y', 1)]);
    const fonts = useFontStore.getState().fonts;
    expect(fonts.map((f) => f.id)).toEqual([1, 2, 3]);
    expect(fonts.map((f) => f.family)).toEqual(['Existing', 'X', 'Y']);
  });

  it('remove drops only the matching id; hydrate replaces wholesale', () => {
    const a = useFontStore.getState().add(asset('A'));
    useFontStore.getState().add(asset('B'));
    useFontStore.getState().remove(a.id);
    expect(useFontStore.getState().fonts.map((f) => f.family)).toEqual(['B']);
    useFontStore.getState().hydrate([asset('Loaded', 5)]);
    expect(useFontStore.getState().fonts).toHaveLength(1);
    expect(useFontStore.getState().fonts[0].family).toBe('Loaded');
  });
});
