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

import {
  buildOnlineStandardizationQueueFingerprint,
  getStoredOnlineStandardizationQueue,
  saveStoredOnlineStandardizationQueue,
  type OnlineStandardizationQueueItem,
} from '@/lib/standardizationQueueStorage';

describe('standardizationQueueStorage', () => {
  beforeEach(() => {
    const storage = new Map<string, string>();
    Object.defineProperty(window, 'localStorage', {
      configurable: true,
      value: {
        getItem: (key: string) => storage.get(key) ?? null,
        setItem: (key: string, value: string) => {
          storage.set(key, value);
        },
        removeItem: (key: string) => {
          storage.delete(key);
        },
        clear: () => {
          storage.clear();
        },
      },
    });

    window.localStorage.clear();
  });

  it('builds a stable fingerprint from sorted material ids', () => {
    expect(buildOnlineStandardizationQueueFingerprint({
      batchId: 'CG-20260412-001',
      materialIds: ['b', 'a'],
      totalRows: 2,
    })).toBe('CG-20260412-001::a,b');
  });

  it('restores persisted queue items and converts submitting back to queued', () => {
    const queue: OnlineStandardizationQueueItem[] = [{
      id: 'queue-1',
      fingerprint: 'CG-20260412-001::all:3',
      batchId: 'CG-20260412-001',
      totalRows: 3,
      createdAt: '2026-04-12T10:00:00.000Z',
      status: 'submitting',
      errorMessage: '',
      blockedUntil: null,
    }];

    saveStoredOnlineStandardizationQueue(queue);

    expect(getStoredOnlineStandardizationQueue()).toEqual([{
      ...queue[0],
      materials: undefined,
      status: 'queued',
    }]);
  });

  it('drops persisted material snapshots and invalid blockedUntil values', () => {
    window.localStorage.setItem('autoprocurement.standardization.online-queue', JSON.stringify([{
      id: 'queue-2',
      fingerprint: 'CG-20260412-002::mat-1',
      batchId: 'CG-20260412-002',
      totalRows: 1,
      createdAt: '2026-04-13T08:00:00.000Z',
      status: 'queued',
      errorMessage: '',
      blockedUntil: 'not-a-date',
      materialIds: ['mat-1'],
      materials: [{
        id: 'mat-1',
        material_name: '测试物料',
        specification: '测试规格',
        quantity: 1,
        unit: '件',
        invoice_type: '专票',
        brand: '测试品牌',
        remarks: '',
        delivery_address: '上海',
      }],
    }]));

    expect(getStoredOnlineStandardizationQueue()).toEqual([{
      id: 'queue-2',
      fingerprint: 'CG-20260412-002::mat-1',
      batchId: 'CG-20260412-002',
      totalRows: 1,
      createdAt: '2026-04-13T08:00:00.000Z',
      status: 'queued',
      errorMessage: '',
      blockedUntil: null,
      materialIds: ['mat-1'],
      materials: undefined,
    }]);
  });

  it('drops invalid payloads from localStorage', () => {
    window.localStorage.setItem('autoprocurement.standardization.online-queue', '{"bad":true}');

    expect(getStoredOnlineStandardizationQueue()).toEqual([]);
    expect(window.localStorage.getItem('autoprocurement.standardization.online-queue')).toBeNull();
  });
});