const segmentLabelMap = {
  partsTaxable: "Parts Taxable",
  partsNonTaxable: "Parts Non-Taxable",
  extrasTaxable: "Extras Taxable",
  extrasNonTaxable: "Extras Non-Taxable",
  laborTaxable: "Labor Taxable",
  laborNonTaxable: "Labor Non-Taxable"
};

const toCentsFromAmountString = (value) => {
  const parsed = Number.parseFloat(value || "0");
  return Number.isNaN(parsed) ? 0 : Math.round(parsed * 100);
};

const buildRoggRows = (rogg) => {
  if (!rogg || !Array.isArray(rogg.ops)) return [];

  const rows = [];

  rogg.ops.forEach((op) => {
    (op.lines || []).forEach((line, idx) => {
      const segmentKind = op.segmentKind;
      const segmentCount = op.segmentCount || 0;
      const segmentLabel = segmentLabelMap[segmentKind] || segmentKind;
      const itemDesc =
        segmentCount > 1 && segmentLabel ? `${line.itemDesc} (${segmentLabel})` : line.itemDesc;

      rows.push({
        key: `${op.jobNo}-${idx}`,
        opCode: op.opCode,
        jobNo: op.jobNo,
        breakOut: line.breakOut,
        itemType: line.itemType,
        itemDesc,
        custQty: line.custQty,
        custPayTypeFlag: line.custPayTypeFlag,
        custTxblNtxblFlag: line.custTxblNtxblFlag,
        custPrice: line.amount?.custPrice,
        dlrCost: line.amount?.dlrCost,
        segmentKind,
        segmentCount
      });
    });
  });

  return rows;
};

const buildRoggTotals = (roggRows) => {
  const totals = roggRows.reduce(
    (acc, row) => {
      acc.totalCustPriceCents += toCentsFromAmountString(row.custPrice);
      acc.totalDlrCostCents += toCentsFromAmountString(row.dlrCost);
      return acc;
    },
    { totalCustPriceCents: 0, totalDlrCostCents: 0 }
  );

  return {
    ...totals,
    totalCustPrice: (totals.totalCustPriceCents / 100).toFixed(2),
    totalDlrCost: (totals.totalDlrCostCents / 100).toFixed(2)
  };
};

const buildRRPreviewMetadata = ({ payload, result } = {}) => {
  const rogg = payload?.rogg || null;
  const roggRows = buildRoggRows(rogg);

  return {
    provider: "rr",
    previewFormat: "rr-rogog-preview.v1",
    roNo: result?.roNo || payload?.roNo || null,
    outsdRoNo: payload?.outsdRoNo || null,
    rogg: {
      raw: rogg,
      rows: roggRows,
      totals: buildRoggTotals(roggRows)
    }
  };
};

module.exports = {
  buildRRPreviewMetadata
};
