import { beforeEach, describe, expect, it } from 'vitest';

import { resolveStoredColumnConfig, saveStoredColumnConfig } from '@/lib/columnConfigStorage';

const storageKey = 'test.column-config';
const currentKeys = ['_index', 'batch_name', 'batch_id', 'material_name', '_actions'];
const oldKeys = ['_index', 'batch_id', 'material_name', '_actions'];

describe('resolveStoredColumnConfig', () => {
  beforeEach(() => {
    window.localStorage.clear();
  });

  it('uses default visible and ordered keys when no stored config exists', () => {
    const result = resolveStoredColumnConfig({
      storageKey,
      allKeys: currentKeys,
      defaultVisibleKeys: currentKeys,
      requiredKeys: ['_index', '_actions'],
    });

    expect(result.orderedKeys).toEqual(currentKeys);
    expect([...result.visibleCols]).toEqual(currentKeys);
  });

  it('inserts newly added columns according to the default order for old stored configs', () => {
    saveStoredColumnConfig(storageKey, {
      orderedKeys: oldKeys,
      visibleKeys: oldKeys,
    });

    const result = resolveStoredColumnConfig({
      storageKey,
      allKeys: currentKeys,
      defaultVisibleKeys: currentKeys,
      requiredKeys: ['_index', '_actions'],
    });

    expect(result.orderedKeys).toEqual(currentKeys);
    expect(result.visibleCols.has('batch_name')).toBe(true);
  });

  it('does not make previously hidden existing columns visible again', () => {
    saveStoredColumnConfig(storageKey, {
      orderedKeys: oldKeys,
      visibleKeys: ['_index', 'batch_id', '_actions'],
    });

    const result = resolveStoredColumnConfig({
      storageKey,
      allKeys: currentKeys,
      defaultVisibleKeys: currentKeys,
      requiredKeys: ['_index', '_actions'],
    });

    expect(result.visibleCols.has('batch_name')).toBe(true);
    expect(result.visibleCols.has('material_name')).toBe(false);
  });

  it('always keeps required columns visible even when stored config hid them', () => {
    saveStoredColumnConfig(storageKey, {
      orderedKeys: currentKeys,
      visibleKeys: ['_index', 'batch_id', '_actions'],
    });

    const result = resolveStoredColumnConfig({
      storageKey,
      allKeys: currentKeys,
      defaultVisibleKeys: currentKeys,
      requiredKeys: ['_index', 'batch_name', '_actions'],
    });

    expect(result.orderedKeys).toEqual(currentKeys);
    expect(result.visibleCols.has('batch_name')).toBe(true);
  });
});
