import * as XLSX from 'xlsx';
import { describe, expect, it } from 'vitest';

import { parseStandardizedImportFile } from '@/lib/standardizedImportParser';

function createWorkbookFile(rows: Array<Array<string | number>>) {
  const worksheet = XLSX.utils.aoa_to_sheet(rows);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
  const buffer = XLSX.write(workbook, { type: 'array', bookType: 'xlsx' });

  const file = new File(
    [buffer],
    'standardized-import.xlsx',
    { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' },
  );

  Object.defineProperty(file, 'arrayBuffer', {
    value: async () => buffer,
  });

  return file;
}

describe('parseStandardizedImportFile', () => {
  it('does not fabricate material_id when the template omits the material_id column', async () => {
    const file = createWorkbookFile([
      ['批次ID', '原始名称', '标准化名称'],
      ['BATCH-001', '球墨铸铁井盖', '球墨铸铁井盖重型'],
    ]);

    const result = await parseStandardizedImportFile(file);

    expect(result.rows).toHaveLength(1);
    expect(result.rows[0]).toMatchObject({
      batch_id: 'BATCH-001',
      material_id: '',
      original_name: '球墨铸铁井盖',
      standardized_name: '球墨铸铁井盖重型',
    });
    expect(result.rows[0]?.provided_fields).not.toContain('material_id');
  });

  it('preserves explicit material_id columns and tracks blank optional columns as provided', async () => {
    const file = createWorkbookFile([
      ['批次ID', '物料ID(material_id)', '标准化名称', '备选搜索词'],
      ['BATCH-002', 'mat-012', '莱卡全站仪专用电池', ''],
    ]);

    const result = await parseStandardizedImportFile(file);

    expect(result.rows).toHaveLength(1);
    expect(result.rows[0]).toMatchObject({
      batch_id: 'BATCH-002',
      material_id: 'mat-012',
      standardized_name: '莱卡全站仪专用电池',
      alt_search_terms: [],
    });
    expect(result.rows[0]?.provided_fields).toEqual(expect.arrayContaining(['material_id', 'standardized_name', 'alt_search_terms']));
  });
});
