import { describe, expect, it } from 'vitest';
import { CURRENT_FONT_VERSION } from '@core/font-asset';
import { migrateFontAsset } from './font-migrations';

const buf = (n: number): ArrayBuffer => new Uint8Array(n).buffer;

describe('migrateFontAsset', () => {
  it('passes a current record through unchanged (plus version stamp)', () => {
    const record = {
      id: 4,
      version: CURRENT_FONT_VERSION,
      family: 'Brand Sans',
      data: buf(2048),
      format: 'woff2' as const,
      fileName: 'Brand-Sans.woff2',
      source: 'file' as const,
      size: 2048,
      created: '2026-06-15T10:00:00.000Z',
      modified: '2026-06-15T10:00:00.000Z',
    };
    expect(migrateFontAsset(record)).toEqual(record);
  });

  it('fills missing or invalid fields with safe defaults', () => {
    const migrated = migrateFontAsset({ id: '9', fileName: 'x.ttf' });
    expect(migrated.id).toBe(9);
    expect(migrated.version).toBe(CURRENT_FONT_VERSION);
    expect(migrated.family).toBe('Custom font');
    expect(migrated.format).toBe('ttf'); // recovered from the file extension
    expect(migrated.data).toBeInstanceOf(ArrayBuffer);
    expect(migrated.size).toBe(0);
    expect(migrated.source).toBe('file');
  });

  it('keeps valid variation axes and drops a malformed axes value', () => {
    const withAxes = migrateFontAsset({
      id: 2,
      family: 'Fixel',
      data: buf(1),
      format: 'ttf',
      fileName: 'Fixel.ttf',
      axes: [{ tag: 'wght', min: 100, default: 400, max: 900 }],
    });
    expect(withAxes.axes).toEqual([{ tag: 'wght', min: 100, default: 400, max: 900 }]);

    const badAxes = migrateFontAsset({
      id: 3,
      family: 'X',
      data: buf(1),
      format: 'ttf',
      fileName: 'x.ttf',
      axes: 'not-an-array',
    });
    expect(badAxes.axes).toBeUndefined();
  });

  it('keeps unknown fields written by a newer build', () => {
    const migrated = migrateFontAsset({
      id: 1,
      family: 'Next',
      data: buf(1),
      format: 'otf',
      fileName: 'n.otf',
      futureField: 'kept',
    });
    expect((migrated as unknown as Record<string, unknown>).futureField).toBe('kept');
  });
});
