/**
 * Customer PO process flow — statuses derived from linked documents only (no duplicated business data).
 * Stages: planning → nesting → material request → issue/purchase → PO material receipt → work order →
 * route card → QC → packing → dispatch → sales invoice.
 */
const { Op } = require('sequelize');
const db = require('../models');

const EPS = 0.0005;
const round3 = (v) => Number((parseFloat(v || 0) || 0).toFixed(3));

const STAGE_KEYS = [
  'PRODUCTION_PLANNING',
  'NESTING',
  'MATERIAL_REQUEST',
  'MATERIAL_ISSUE_PURCHASE',
  'PRODUCTION_MATERIAL_RECEIPT',
  'WORK_ORDER',
  'ROUTE_CARD',
  'QUALITY_CHECK',
  'PACKING',
  'DISPATCH',
  'SALES_INVOICE',
];

const STAGE_LABELS = {
  PRODUCTION_PLANNING: 'Production Planning',
  NESTING: 'Nesting',
  MATERIAL_REQUEST: 'Material Request',
  MATERIAL_ISSUE_PURCHASE: 'Material Issue / Purchase',
  PRODUCTION_MATERIAL_RECEIPT: 'Production Material Receipt',
  WORK_ORDER: 'Work Order',
  ROUTE_CARD: 'Route Card Execution',
  QUALITY_CHECK: 'Quality Check (QC)',
  PACKING: 'Packing',
  DISPATCH: 'Dispatch',
  SALES_INVOICE: 'Sales / Invoice',
};

function activePOs(pos) {
  return pos.filter((p) => String(p.status || '') !== 'CANCELLED');
}

/**
 * @param {number} customerPoId
 * @param {{ companyId?: number, isSuperAdmin?: boolean }} ctx
 */
async function buildProcessFlow(customerPoId, ctx = {}) {
  const cpo = await db.CustomerPO.findByPk(customerPoId, {
    attributes: [
      'id',
      'company_id',
      'plant_id',
      'po_number',
      'status',
      'created_at',
      'updated_at',
    ],
    include: [
      {
        model: db.CustomerPOItem,
        as: 'items',
        attributes: ['id', 'item_number', 'material_id', 'quantity', 'delivered_quantity', 'description'],
        required: false,
      },
    ],
  });

  if (!cpo) return null;

  if (
    ctx.companyId != null &&
    !ctx.isSuperAdmin &&
    Number(cpo.company_id) !== Number(ctx.companyId)
  ) {
    return { forbidden: true };
  }

  const poIds = (
    await db.ProductionOrder.findAll({
      where: { customer_po_id: customerPoId },
      attributes: [
        'id',
        'production_order_number',
        'status',
        'is_sent_to_nesting',
        'nesting_number',
        'created_at',
        'updated_at',
        'released_at',
      ],
    })
  ).map((r) => (typeof r.toJSON === 'function' ? r.toJSON() : r));

  const active = activePOs(poIds);
  const poIdList = active.map((p) => p.id);

  const [
    workOrders,
    routeCards,
    materialRequests,
    materialIssues,
    receiptAgg,
    nestingStores,
    nestingConfirmRows,
    packings,
    qcs,
    fais,
    deliveries,
    invoices,
    inProgMrRows,
  ] = await Promise.all([
    poIdList.length
      ? db.WorkOrder.findAll({
          where: { production_order_id: { [Op.in]: poIdList } },
          attributes: ['id', 'work_order_number', 'production_order_id', 'status', 'created_at', 'updated_at'],
        })
      : [],
    poIdList.length
      ? db.RouteCard.findAll({
          where: { production_order_id: { [Op.in]: poIdList } },
          attributes: ['id', 'route_card_number', 'work_order_id', 'production_order_id', 'status', 'created_at', 'updated_at'],
        })
      : [],
    poIdList.length
      ? db.MaterialRequest.findAll({
          where: { production_order_id: { [Op.in]: poIdList } },
          attributes: ['id', 'request_number', 'production_order_id', 'status', 'created_at', 'updated_at'],
        })
      : [],
    poIdList.length
      ? db.MaterialIssue.findAll({
          where: { production_order_id: { [Op.in]: poIdList } },
          attributes: ['id', 'issue_number', 'production_order_id', 'status', 'created_at', 'updated_at'],
        })
      : [],
    poIdList.length
      ? db.ProductionOrderMaterialReceiptLine.findAll({
          where: { production_order_id: { [Op.in]: poIdList } },
          attributes: ['id', 'production_order_id', 'received_qty', 'created_at'],
        })
      : [],
    poIdList.length
      ? db.NestingStoresRequest.findAll({
          where: {
            [Op.or]: [{ customer_po_id: customerPoId }, { production_order_id: { [Op.in]: poIdList } }],
          },
          attributes: ['id', 'production_order_id', 'customer_po_id', 'created_at'],
        })
      : db.NestingStoresRequest.findAll({
          where: { customer_po_id: customerPoId },
          attributes: ['id', 'production_order_id', 'customer_po_id', 'created_at'],
        }),
    poIdList.length
      ? db.ProductionNestingConfirmation.findAll({
          where: { production_order_id: { [Op.in]: poIdList } },
          attributes: ['id', 'production_order_id', 'created_at'],
        })
      : [],
    poIdList.length
      ? db.ProductionPacking.findAll({
          where: { production_order_id: { [Op.in]: poIdList } },
          attributes: ['id', 'packing_number', 'production_order_id', 'route_card_id', 'packed_qty', 'created_at'],
        })
      : [],
    poIdList.length
      ? db.ProductionQC.findAll({
          where: { production_order_id: { [Op.in]: poIdList } },
          attributes: ['id', 'production_qc_number', 'production_order_id', 'route_card_id', 'status', 'created_at', 'updated_at'],
        })
      : [],
    poIdList.length
      ? db.ProductionFinalInspection.findAll({
          where: { production_order_id: { [Op.in]: poIdList } },
          attributes: ['id', 'final_inspection_number', 'production_order_id', 'route_card_id', 'status', 'created_at'],
        })
      : [],
    db.Delivery.findAll({
      where: { customer_po_id: customerPoId },
      attributes: ['id', 'delivery_number', 'status', 'posted_at', 'created_at', 'updated_at'],
    }),
    db.SalesInvoice.findAll({
      where: { customer_po_id: customerPoId },
      attributes: [
        'id',
        'invoice_number',
        'status',
        'posted_at',
        'dispatch_status',
        'dispatched_qty',
        'created_at',
        'updated_at',
      ],
    }),
    db.InProgressMaterialRequest.findAll({
      where: { customer_po_id: customerPoId },
      attributes: ['id', 'ipmr_number', 'material_request_number', 'status', 'created_at'],
    }),
  ]);

  const woList = workOrders.map((x) => x.toJSON());
  const rcList = routeCards.map((x) => x.toJSON());
  const mrList = materialRequests.map((x) => x.toJSON());
  const miList = materialIssues.map((x) => x.toJSON());
  const rcptList = receiptAgg.map((x) => x.toJSON());
  const nsrList = nestingStores.map((x) => x.toJSON());
  const nestConf = nestingConfirmRows.map((x) => x.toJSON());
  const packList = packings.map((x) => x.toJSON());
  const qcList = qcs.map((x) => x.toJSON());
  const faiList = fais.map((x) => x.toJSON());
  const delList = deliveries.map((x) => x.toJSON());
  const invList = invoices.map((x) => x.toJSON());
  const ipMrList = inProgMrRows.map((x) => x.toJSON());

  const items = (cpo.items || []).map((i) => (typeof i.toJSON === 'function' ? i.toJSON() : i));
  const orderedQty = items.reduce((s, it) => s + round3(it.quantity), 0);
  const deliveredQty = items.reduce((s, it) => s + round3(it.delivered_quantity), 0);
  const balanceQty = Math.max(0, round3(orderedQty - deliveredQty));

  /* --- Production Planning --- */
  let planning = 'NOT_STARTED';
  let planningDetail = 'No production orders linked to this Customer PO.';
  if (active.length > 0) {
    const allDone = active.every((p) => ['CONFIRMED', 'CLOSED'].includes(String(p.status || '')));
    const anyLive = active.some((p) =>
      ['RELEASED', 'IN_PROGRESS', 'PARTIALLY_CONFIRMED'].includes(String(p.status || ''))
    );
    const anyDraft = active.some((p) => String(p.status || '') === 'DRAFT');
    if (allDone) {
      planning = 'COMPLETED';
      planningDetail = `${active.length} production order(s) confirmed or closed.`;
    } else if (anyLive || anyDraft) {
      planning = 'IN_PROGRESS';
      planningDetail = `${active.length} production order(s); statuses include planning / execution.`;
    }
  }

  /* --- Nesting --- */
  let nesting = 'NOT_STARTED';
  let nestingDetail = 'No nesting activity for linked production orders.';
  if (active.length > 0) {
    const hasSignal = (p) =>
      p.is_sent_to_nesting ||
      nsrList.some((n) => n.production_order_id === p.id) ||
      nestConf.some((c) => c.production_order_id === p.id) ||
      (p.nesting_number && String(p.nesting_number).trim() !== '');
    const anySignal = active.some(hasSignal);
    const allClosedOrConfirmed = active.every((p) =>
      ['CONFIRMED', 'CLOSED'].includes(String(p.status || ''))
    );
    const nestingDone = (p) =>
      (p.nesting_number && String(p.nesting_number).trim() !== '') ||
      nestConf.some((c) => c.production_order_id === p.id) ||
      ['CONFIRMED', 'CLOSED'].includes(String(p.status || ''));
    const allNestingDone = active.every(nestingDone);
    if (anySignal && allNestingDone) {
      nesting = 'COMPLETED';
      nestingDetail = 'Nesting signals present and production orders advanced or nesting references recorded.';
    } else if (anySignal) {
      nesting = 'IN_PROGRESS';
      nestingDetail = 'Nesting started (sent to nesting, nesting→stores, or confirmations) — not all POs finalized.';
    }
  }

  /* --- Material Request --- */
  let matReq = 'NOT_STARTED';
  let matReqDetail = 'No material requests for linked production orders.';
  if (mrList.length > 0 || ipMrList.length > 0) {
    const terminal = new Set(['COMPLETED', 'CANCELLED']);
    const allDone = mrList.length > 0 && mrList.every((m) => terminal.has(String(m.status || '')));
    const anyOpen = mrList.some((m) => !terminal.has(String(m.status || '')));
    if (ipMrList.length > 0 && mrList.length === 0) {
      matReq = 'IN_PROGRESS';
      matReqDetail = `${ipMrList.length} in-progress material request (IPMR) record(s) linked to this Customer PO.`;
    } else if (allDone && mrList.length > 0) {
      matReq = 'COMPLETED';
      matReqDetail = 'All material requests completed or cancelled.';
    } else if (anyOpen || ipMrList.length > 0) {
      matReq = 'IN_PROGRESS';
      matReqDetail = 'Material request(s) in workflow (stores / purchase / issue).';
    }
  }

  /* --- Material Issue / Purchase --- */
  let matIss = 'NOT_STARTED';
  let matIssDetail = 'No material issues recorded for linked production orders.';
  if (mrList.length > 0 || miList.length > 0) {
    const mrPurchase = mrList.some((m) =>
      ['SENT_TO_PURCHASE', 'REVIEWED', 'SENT_TO_STORES'].includes(String(m.status || ''))
    );
    const miPending = miList.some((m) => ['DRAFT', 'IN_TRANSIT'].includes(String(m.status || '')));
    const miDone =
      miList.length > 0 &&
      miList.every((m) => ['POSTED', 'RECEIVED', 'CANCELLED'].includes(String(m.status || '')));
    const mrDone =
      mrList.length === 0 ||
      mrList.every((m) => ['COMPLETED', 'CANCELLED'].includes(String(m.status || '')));
    if (mrDone && (miList.length === 0 || miDone)) {
      matIss = mrList.length === 0 && miList.length === 0 ? 'NOT_STARTED' : 'COMPLETED';
      matIssDetail =
        miList.length > 0
          ? 'Material issues posted or received.'
          : 'No open material issues; requests closed without issue records.';
    } else if (miPending || mrPurchase || miList.length > 0) {
      matIss = 'IN_PROGRESS';
      matIssDetail = mrPurchase
        ? 'Purchase path may be active (MR sent to purchase). '
        : '';
      matIssDetail += miPending ? 'Some material issues still in draft or in transit.' : 'Fulfillment in progress.';
    }
  }

  /* --- Production material receipt (to production / WIP) --- */
  let pmr = 'NOT_STARTED';
  let pmrDetail = 'No production material receipt lines.';
  if (rcptList.length > 0) {
    const qty = rcptList.reduce((s, l) => s + round3(l.received_qty), 0);
    if (qty > EPS) {
      pmr = 'COMPLETED';
      pmrDetail = `${rcptList.length} receipt line(s); total received qty ${qty.toFixed(3)}.`;
    }
  } else if (miList.some((m) => ['RECEIVED', 'POSTED'].includes(String(m.status || '')))) {
    pmr = 'IN_PROGRESS';
    pmrDetail = 'Material issued/received; add PO material receipt lines if used for this flow.';
  }

  /* --- Work Order --- */
  let woSt = 'NOT_STARTED';
  let woDetail = 'No work orders for linked production orders.';
  if (woList.length > 0) {
    const allWoDone = woList.every((w) => ['COMPLETED', 'CLOSED'].includes(String(w.status || '')));
    const anyWoLive = woList.some((w) => ['RELEASED', 'IN_PROGRESS'].includes(String(w.status || '')));
    if (allWoDone) {
      woSt = 'COMPLETED';
      woDetail = `${woList.length} work order(s) completed or closed.`;
    } else if (anyWoLive || woList.some((w) => String(w.status || '') === 'PLANNED')) {
      woSt = 'IN_PROGRESS';
      woDetail = `${woList.length} work order(s) in planning or execution.`;
    }
  }

  /* --- Route Card --- */
  let rcSt = 'NOT_STARTED';
  let rcDetail = 'No route cards for linked production orders.';
  if (rcList.length > 0) {
    const allClosed = rcList.every((r) => String(r.status || '') === 'CLOSED');
    const anyOpen = rcList.some((r) => String(r.status || '') === 'OPEN');
    if (allClosed) {
      rcSt = 'COMPLETED';
      rcDetail = `${rcList.length} route card(s) closed.`;
    } else if (anyOpen) {
      rcSt = 'IN_PROGRESS';
      rcDetail = `${rcList.length} route card(s); at least one open.`;
    }
  }

  /* --- QC (operation QC + final inspection) --- */
  let qcSt = 'NOT_STARTED';
  let qcDetail = 'No QC or final inspection records.';
  if (qcList.length > 0 || faiList.length > 0) {
    const pendingQc = qcList.filter((q) => !['COMPLETED', 'APPROVED'].includes(String(q.status || ''))).length;
    const pendingFai = faiList.filter((f) => String(f.status || '') !== 'COMPLETED').length;
    if (pendingQc === 0 && pendingFai === 0) {
      qcSt = 'COMPLETED';
      qcDetail = 'QC and final inspection (if any) completed.';
    } else {
      qcSt = 'IN_PROGRESS';
      qcDetail = `QC / inspection in progress (${pendingQc} op. QC pending, ${pendingFai} FAI pending).`;
    }
  }

  /* --- Packing --- */
  let packSt = 'NOT_STARTED';
  let packDetail = 'No packing records.';
  if (packList.length > 0) {
    const totalPacked = packList.reduce((s, p) => s + round3(p.packed_qty), 0);
    if (totalPacked > EPS) {
      packSt = 'COMPLETED';
      packDetail = `${packList.length} packing record(s); packed qty ${totalPacked.toFixed(3)}.`;
    } else {
      packSt = 'IN_PROGRESS';
      packDetail = `${packList.length} packing record(s) created.`;
    }
  }

  /* --- Dispatch --- */
  let dispSt = 'NOT_STARTED';
  let dispDetail = 'No deliveries linked to this Customer PO.';
  if (delList.length > 0) {
    const posted = delList.filter((d) => d.posted_at && String(d.status || '') === 'POSTED');
    if (posted.length === delList.length) {
      dispSt = 'COMPLETED';
      dispDetail = `${delList.length} delivery document(s) posted.`;
    } else {
      dispSt = 'IN_PROGRESS';
      dispDetail = `${delList.length} delivery document(s); awaiting post where applicable.`;
    }
  }

  /* --- Sales Invoice --- */
  let invSt = 'NOT_STARTED';
  let invDetail = 'No sales invoices linked to this Customer PO.';
  if (invList.length > 0) {
    const posted = invList.filter((i) => i.posted_at && String(i.status || '') === 'APPROVED');
    const fullDisp = invList.every((i) => String(i.dispatch_status || '') === 'FULLY_DISPATCHED');
    if (posted.length === invList.length && fullDisp) {
      invSt = 'COMPLETED';
      invDetail = 'Invoice(s) approved/posted and dispatch marked fully dispatched.';
    } else {
      invSt = 'IN_PROGRESS';
      invDetail = 'Invoice(s) in draft or dispatch not fully completed.';
    }
  }

  const stageMap = {
    PRODUCTION_PLANNING: { status: planning, detail: planningDetail },
    NESTING: { status: nesting, detail: nestingDetail },
    MATERIAL_REQUEST: { status: matReq, detail: matReqDetail },
    MATERIAL_ISSUE_PURCHASE: { status: matIss, detail: matIssDetail },
    PRODUCTION_MATERIAL_RECEIPT: { status: pmr, detail: pmrDetail },
    WORK_ORDER: { status: woSt, detail: woDetail },
    ROUTE_CARD: { status: rcSt, detail: rcDetail },
    QUALITY_CHECK: { status: qcSt, detail: qcDetail },
    PACKING: { status: packSt, detail: packDetail },
    DISPATCH: { status: dispSt, detail: dispDetail },
    SALES_INVOICE: { status: invSt, detail: invDetail },
  };

  const completedCount = STAGE_KEYS.filter((k) => stageMap[k].status === 'COMPLETED').length;
  const progressPercent = Math.round((completedCount / STAGE_KEYS.length) * 100);

  const pendingActions = [];
  if (planning === 'IN_PROGRESS') pendingActions.push('Production planning / production orders in progress');
  if (nesting === 'IN_PROGRESS') pendingActions.push('Nesting pending');
  if (matReq === 'IN_PROGRESS') pendingActions.push('Material request pending');
  if (matIss === 'IN_PROGRESS') pendingActions.push('Material issue or purchase follow-up pending');
  if (pmr === 'NOT_STARTED' && miList.some((m) => ['RECEIVED', 'POSTED'].includes(String(m.status || ''))))
    pendingActions.push('Production material receipt (lines) may need recording');
  if (woSt === 'IN_PROGRESS') pendingActions.push('Work order execution pending');
  if (rcSt === 'IN_PROGRESS') pendingActions.push('Route card execution pending');
  if (qcSt === 'IN_PROGRESS') pendingActions.push('QC / final inspection pending');
  if (packSt === 'IN_PROGRESS') pendingActions.push('Packing pending');
  if (dispSt === 'IN_PROGRESS') pendingActions.push('Dispatch pending');
  if (invSt === 'IN_PROGRESS') pendingActions.push('Sales invoice / dispatch completion pending');
  if (balanceQty > EPS) pendingActions.push(`Balance quantity to fulfill: ${balanceQty.toFixed(3)}`);

  const links = {
    PRODUCTION_PLANNING: poIds.map((p) => ({
      label: `Production Order ${p.production_order_number}`,
      path: `/production/production-order/${p.id}/view`,
      refType: 'production_order',
      refId: p.id,
    })),
    NESTING: [
      ...new Set(
        active
          .filter((p) => p.is_sent_to_nesting || nsrList.some((n) => n.production_order_id === p.id))
          .map((p) => p.id)
      ),
    ].map((pid) => ({
      label: `Nesting (PO #${active.find((x) => x.id === pid)?.production_order_number || pid})`,
      path: `/production/nesting/${pid}/view`,
      refType: 'nesting',
      refId: pid,
    })),
    MATERIAL_REQUEST: [
      ...mrList.map((m) => ({
        label: `Material Request ${m.request_number}`,
        path: `/stores/materialrequest/${m.id}/view`,
        refType: 'material_request',
        refId: m.id,
      })),
      ...ipMrList.map((m) => ({
        label: `IPMR ${m.ipmr_number || m.id}`,
        path: `/production/inprogress-material-request/${m.id}/view`,
        refType: 'in_progress_material_request',
        refId: m.id,
      })),
    ],
    MATERIAL_ISSUE_PURCHASE: miList.map((m) => ({
      label: `Material Issue ${m.issue_number}`,
      path: `/production/materialissue/${m.id}/view`,
      refType: 'material_issue',
      refId: m.id,
    })),
    PRODUCTION_MATERIAL_RECEIPT: poIdList.map((pid) => ({
      label: `Material receipt (PO #${active.find((x) => x.id === pid)?.production_order_number || pid})`,
      path: `/production/materialreceive?production_order_id=${pid}`,
      refType: 'production_material_receipt',
      refId: pid,
    })),
    WORK_ORDER: woList.map((w) => ({
      label: `Work Order ${w.work_order_number}`,
      path: `/production/workorder/${w.id}/view`,
      refType: 'work_order',
      refId: w.id,
    })),
    ROUTE_CARD: rcList.map((r) => ({
      label: `Route Card ${r.route_card_number}`,
      path: `/production/routecard/${r.id}/view`,
      refType: 'route_card',
      refId: r.id,
    })),
    QUALITY_CHECK: [
      ...qcList.map((q) => ({
        label: q.production_qc_number ? `QC ${q.production_qc_number}` : `QC #${q.id}`,
        path: `/production/quality-checking/production-qc/${q.id}/view`,
        refType: 'production_qc',
        refId: q.id,
      })),
      ...faiList.map((f) => ({
        label: f.final_inspection_number ? `FAI ${f.final_inspection_number}` : `FAI #${f.id}`,
        path: `/production/quality-checking/final-inspection/${f.id}/view`,
        refType: 'final_inspection',
        refId: f.id,
      })),
    ],
    PACKING: packList.map((p) => ({
      label: `Packing ${p.packing_number}`,
      path: `/production/packing/${p.id}/view`,
      refType: 'production_packing',
      refId: p.id,
    })),
    DISPATCH: delList.map((d) => ({
      label: `Delivery ${d.delivery_number}`,
      path: `/sales/delivery/${d.id}/view`,
      refType: 'delivery',
      refId: d.id,
    })),
    SALES_INVOICE: invList.map((i) => ({
      label: `Invoice ${i.invoice_number}`,
      path: `/sales/invoice/${i.id}/view`,
      refType: 'sales_invoice',
      refId: i.id,
    })),
  };

  const trail = [];
  const pushTrail = (at, label, refType, refId, path) => {
    if (!at) return;
    trail.push({
      at,
      label,
      refType: refType || null,
      refId: refId || null,
      path: path || null,
    });
  };

  pushTrail(cpo.created_at, 'Customer PO created', 'customer_po', cpo.id, `/customer/po/${cpo.id}/view`);
  for (const p of poIds) {
    pushTrail(
      p.created_at,
      `Production order ${p.production_order_number} created`,
      'production_order',
      p.id,
      `/production/production-order/${p.id}/view`
    );
  }
  for (const m of mrList) {
    pushTrail(
      m.created_at,
      `Material request ${m.request_number} created`,
      'material_request',
      m.id,
      `/stores/materialrequest/${m.id}/view`
    );
  }
  for (const m of miList) {
    pushTrail(
      m.created_at,
      `Material issue ${m.issue_number} created`,
      'material_issue',
      m.id,
      `/production/materialissue/${m.id}/view`
    );
  }
  for (const w of woList) {
    pushTrail(
      w.created_at,
      `Work order ${w.work_order_number} created`,
      'work_order',
      w.id,
      `/production/workorder/${w.id}/view`
    );
  }
  for (const r of rcList) {
    pushTrail(
      r.created_at,
      `Route card ${r.route_card_number} created`,
      'route_card',
      r.id,
      `/production/routecard/${r.id}/view`
    );
  }
  for (const d of delList) {
    pushTrail(
      d.created_at,
      `Delivery ${d.delivery_number} created`,
      'delivery',
      d.id,
      `/sales/delivery/${d.id}/view`
    );
  }
  for (const i of invList) {
    pushTrail(
      i.created_at,
      `Sales invoice ${i.invoice_number} created`,
      'sales_invoice',
      i.id,
      `/sales/invoice/${i.id}/view`
    );
  }

  trail.sort((a, b) => new Date(a.at) - new Date(b.at));

  const stages = STAGE_KEYS.map((key) => ({
    key,
    label: STAGE_LABELS[key],
    status: stageMap[key].status,
    detail: stageMap[key].detail,
    links: links[key] || [],
  }));

  const cpoJson = typeof cpo.toJSON === 'function' ? cpo.toJSON() : cpo;

  return {
    customer_po: {
      id: cpoJson.id,
      po_number: cpoJson.po_number,
      status: cpoJson.status,
    },
    quantities: {
      ordered: orderedQty,
      delivered: deliveredQty,
      balance: balanceQty,
      line_count: items.length,
    },
    progress_percent: progressPercent,
    pending_actions: pendingActions,
    stages,
    document_trail: trail,
    meta: {
      production_order_count: poIds.length,
      work_order_count: woList.length,
      route_card_count: rcList.length,
    },
  };
}

module.exports = {
  buildProcessFlow,
  STAGE_KEYS,
  STAGE_LABELS,
};
