// src/workers/normalizeDn.worker.js
// NOTE: keep this file plain JS - no TS imports - copy needed transform functions here.

// function formatDateToDDMMYYYY(dateString) {
//   if (!dateString) return '';
//   const d = new Date(dateString);
//   const day = String(d.getDate()).padStart(2, '0');
//   const month = String(d.getMonth() + 1).padStart(2, '0');
//   const year = d.getFullYear();
//   return `${day}/${month}/${year}`;
// }

// minimal transform helpers used in normalize
function transformFgStatusToFgSignStatus(fgStatus) {
  const splitted = (fgStatus || '').split('-') || [];
  if (splitted.includes('SIGN') > 0) return 'FAILED';
  if (splitted.includes('SIGNING IN PROGRESS')) return 'IN_PROGRESS';
  switch (splitted[1]) {
    case 'document signed successfully':
    case 'Done':
      return 'SIGNED';
    default:
      return null;
  }
}

function getFgStatusPdf(link, fgSignStatus) {
  if (!link || fgSignStatus === 'IN_PROGRESS') return 'TIDAK_TERSEDIA';
  if (!link.includes('https://coretaxdjp.pajak.go.id/')) return 'BELUM_TERBENTUK';
  return 'TERBENTUK';
}

function normalisePropsGetSsp(params) {
  if (!params) return params;
  return {
    ...params,
    namaDok: params.dokumen_referensi?.[0]?.namaDok || '',
    nomorDok: params.dokumen_referensi?.[0]?.nomorDok || '',
    id: params.id,
    internal_id: params.internal_id,
    fgStatus: params.fgStatus,
    fgSignStatus: transformFgStatusToFgSignStatus(params.fgStatus),
    fgPdf: getFgStatusPdf(params.link, transformFgStatusToFgSignStatus(params.fgStatus)),
  };
}

// eslint-disable-next-line func-names
onmessage = function (e) {
  const { data } = e;
  // data should be array of items
  if (!Array.isArray(data)) {
    postMessage({ error: 'expected array' });
    return;
  }
  try {
    const out = data.map(normalisePropsGetSsp);
    console.log(out);
    postMessage({ data: out });
  } catch (err) {
    postMessage({ error: (err && err.message) || String(err) });
  }
};
