import { deflateRawSync } from 'node:zlib';
import { describe, expect, it } from 'vitest';
import { readXlsxSheets } from '../common/xlsx-read';
import { writeXlsxBytes } from '../common/xlsx-write';
import { parseMasterWorkbook } from './master-data.import';
import { fromLabel, parseCell, parseDate, toCell } from './master-data.workbook';

describe('xlsx write → read', () => {
  it('reads back every sheet, by name, cell for cell', () => {
    const bytes = writeXlsxBytes([
      { name: '說明', columns: [], rows: [{ cells: ['主檔 & <資料> "x"'] }] },
      {
        name: '租約',
        columns: [{ width: 10 }, { money: true }],
        rows: [{ cells: ['租約編號', '金額'], bold: true }, { cells: ['L-001', 65000.5] }, { cells: [null, 12] }],
      },
    ]);
    const sheets = readXlsxSheets(bytes);
    expect(sheets.map((s) => s.name)).toEqual(['說明', '租約']);
    expect(sheets[0].rows).toEqual([['主檔 & <資料> "x"']]);
    expect(sheets[1].rows).toEqual([['租約編號', '金額'], ['L-001', '65000.5'], ['', '12']]);
  });

  it('gives two sheets of one name names Excel will open', () => {
    const sheets = readXlsxSheets(writeXlsxBytes([{ name: 'A', columns: [], rows: [] }, { name: 'a', columns: [], rows: [] }]));
    expect(sheets.map((s) => s.name)).toEqual(['A', 'a 2']);
  });

  it('reads a compressed workbook, as Excel saves one', () => {
    // Re-pack a written workbook with every part deflated.
    const stored = writeXlsxBytes([{ name: 'S', columns: [], rows: [{ cells: ['x', 1] }] }]);
    const parts = storedParts(stored);
    const sheets = readXlsxSheets(deflatedZip(parts));
    expect(sheets[0].rows).toEqual([['x', '1']]);
  });
});

describe('cells', () => {
  it('reads a date typed in Excel, the workbook\'s own text, and YYYY/M/D', () => {
    expect(parseDate('46843')).toBe('2028-03-31');
    expect(parseDate('2026-04-01')).toBe('2026-04-01');
    expect(parseDate('2026/4/1')).toBe('2026-04-01');
    expect(() => parseDate('2026-02-30')).toThrow();
    expect(() => parseDate('放租中')).toThrow();
  });

  it('reads yes/no, whole numbers and amounts, and says what is wrong', () => {
    expect(parseCell('bool', '是')).toBe(true);
    expect(parseCell('bool', 'N')).toBe(false);
    expect(() => parseCell('bool', 'maybe')).toThrow('是/否');
    expect(parseCell('int', '3')).toBe(3);
    expect(() => parseCell('int', '3.5')).toThrow('整數');
    expect(parseCell('money', '1,234.567')).toBe(1234.57);
    expect(parseCell('money', '')).toBeNull();
  });

  it('writes what it reads back', () => {
    expect(toCell('bool', true)).toBe('是');
    expect(toCell('money', '65000.00')).toBe(65000);
    expect(toCell('date', '2026-04-01')).toBe('2026-04-01');
    expect(toCell('text', null)).toBeNull();
  });

  it('takes a list value as its label or its word', () => {
    expect(fromLabel('status', '生效中')).toBe('ACTIVE');
    expect(fromLabel('status', 'ended')).toBe('ENDED');
    expect(fromLabel('timing', '後繳')).toBe('ARREARS');
    expect(fromLabel('status', '放租中')).toBeUndefined();
  });
});

describe('reading the workbook', () => {
  it('names the sheet, the row and the column of each problem, and skips sheets it does not know', () => {
    const bytes = writeXlsxBytes([
      { name: '核對清單', columns: [], rows: [{ cells: ['anything'] }] },
      { name: '單位', columns: [], rows: [{ cells: ['物業編號'] }, { cells: ['P1'] }] },
      {
        name: '租約收費',
        columns: [],
        rows: [{ cells: ['租約編號', '收費類型', '金額', '每幾個月'] }, { cells: ['L1', 'RENT', 'abc', '1'] }, { cells: ['', '', '', ''] }, { cells: ['L1', '', '10', '1'] }],
      },
    ]);
    const { data, problems } = parseMasterWorkbook(readXlsxSheets(bytes));
    expect(problems).toEqual([
      '「單位」缺少欄位:單位',
      '「租約收費」第 2 行「金額」:「abc」不是數字',
      '「租約收費」第 4 行「收費類型」不可留空',
    ]);
    expect(data.charges.map((r) => r.line)).toEqual([2, 4]);
    expect(data.units).toEqual([]);
    expect(data.leases).toEqual([]);
  });
});

// ── a deflated copy of a stored zip, for the reader's other path ──

function storedParts(zip: Uint8Array): [string, Uint8Array][] {
  const view = new DataView(zip.buffer, zip.byteOffset, zip.byteLength);
  const out: [string, Uint8Array][] = [];
  let at = 0;
  while (view.getUint32(at, true) === 0x04034b50) {
    const size = view.getUint32(at + 18, true);
    const nameLen = view.getUint16(at + 26, true);
    const name = new TextDecoder().decode(zip.subarray(at + 30, at + 30 + nameLen));
    out.push([name, zip.subarray(at + 30 + nameLen, at + 30 + nameLen + size)]);
    at += 30 + nameLen + size;
  }
  return out;
}

function deflatedZip(files: [string, Uint8Array][]): Uint8Array {
  const chunks: Buffer[] = [];
  const central: Buffer[] = [];
  let offset = 0;
  for (const [name, data] of files) {
    const nameBytes = Buffer.from(name);
    const packed = deflateRawSync(data);
    const local = Buffer.alloc(30);
    local.writeUInt32LE(0x04034b50, 0);
    local.writeUInt16LE(20, 4);
    local.writeUInt16LE(8, 8);
    local.writeUInt32LE(packed.length, 18);
    local.writeUInt32LE(data.length, 22);
    local.writeUInt16LE(nameBytes.length, 26);
    chunks.push(local, nameBytes, packed);
    const entry = Buffer.alloc(46);
    entry.writeUInt32LE(0x02014b50, 0);
    entry.writeUInt16LE(8, 10);
    entry.writeUInt32LE(packed.length, 20);
    entry.writeUInt32LE(data.length, 24);
    entry.writeUInt16LE(nameBytes.length, 28);
    entry.writeUInt32LE(offset, 42);
    central.push(entry, nameBytes);
    offset += 30 + nameBytes.length + packed.length;
  }
  const centralSize = central.reduce((n, c) => n + c.length, 0);
  const end = Buffer.alloc(22);
  end.writeUInt32LE(0x06054b50, 0);
  end.writeUInt16LE(files.length, 8);
  end.writeUInt16LE(files.length, 10);
  end.writeUInt32LE(centralSize, 12);
  end.writeUInt32LE(offset, 16);
  return Buffer.concat([...chunks, ...central, end]);
}
