import type { MileageExportInput, MileageWorkbookRow, MileageExportVehicle } from './mileageExport';
import { createMileageWorkbook } from './mileageWorkbook';
import { transferableWorkbookBuffer } from './transferableBuffer';

type MileageWorkerResponse = { ok: true; buffer: ArrayBuffer } | { ok: false; message: string };
type MileageWorkerRequest =
  | { type: 'start'; input: Omit<MileageExportInput, 'vehicles' | 'mileageRows'> }
  | { type: 'rows'; rows: MileageWorkbookRow[] }
  | { type: 'finish'; vehicles: MileageExportVehicle[] };
type WorkerScope = {
  onmessage: ((event: MessageEvent<MileageWorkerRequest>) => void) | null;
  postMessage: (message: MileageWorkerResponse, transfer?: Transferable[]) => void;
};

const workerScope = self as unknown as WorkerScope;
let baseInput: Omit<MileageExportInput, 'vehicles' | 'mileageRows'> | undefined;
let mileageRows: MileageWorkbookRow[] = [];

workerScope.onmessage = async (event) => {
  if (event.data.type === 'start') {
    baseInput = event.data.input;
    mileageRows = [];
    return;
  }
  if (event.data.type === 'rows') {
    mileageRows.push(...event.data.rows);
    return;
  }
  try {
    if (!baseInput) throw new Error('Excel 工作线程未初始化');
    const workbook = await createMileageWorkbook({ ...baseInput, vehicles: event.data.vehicles, mileageRows });
    mileageRows = [];
    const output = await workbook.xlsx.writeBuffer();
    const buffer = transferableWorkbookBuffer(output as ArrayBuffer | Uint8Array);
    workerScope.postMessage({ ok: true, buffer }, [buffer]);
  } catch (error) {
    mileageRows = [];
    workerScope.postMessage({
      ok: false,
      message: error instanceof Error ? error.message : 'Excel 工作簿生成失败'
    });
  }
};
