/**
 * ORAC assessment row categorization — aligned with Risk Assessment executor dashboard trend logic.
 */

export function getAssessmentStatusLabel(row) {
  return row.assessment_status_name || `Status ${row.assessment_status_id}`;
}

export function isReturnedWaitingOnExecutor(row) {
  const l = getAssessmentStatusLabel(row).toLowerCase();
  if (l.includes("returned")) return true;
  if (l.includes("return") && l.includes("executor")) return true;
  return false;
}

export function isReturnByVerifier(row) {
  return isReturnedWaitingOnExecutor(row);
}

function isVerificationRequiredStatus(row, normalizedLabel) {
  if (row.assessment_status_id === 5) return true;
  const l = normalizedLabel;
  if (l.includes("varific")) return true;
  return l.includes("verif") && l.includes("requir");
}

export function categorizeExecutorRow(row) {
  const l = getAssessmentStatusLabel(row).toLowerCase();
  if (isReturnByVerifier(row)) return "returned";
  if (isVerificationRequiredStatus(row, l)) return "verification_required";
  if (l.includes("complete") || l.includes("done")) return "done";
  if (l.includes("progress") || l.includes("ongoing") || l.includes("in process")) return "not_started";
  if (row.assessment_status_id === 3) return "not_started";
  if (l.includes("not started") || row.assessment_status_id === 1) return "not_started";
  return "other";
}

export function categorizeVerifierRow(row) {
  const id = Number(row?.assessment_status_id);
  const raw = row?.vf_max_occurrence;
  const vfMax = raw == null || raw === "" ? 0 : Number(raw);
  const vfOk = Number.isFinite(vfMax) ? vfMax : 0;
  if (id === 5 && vfOk < 1) {
    return "not_started";
  }
  if (Number.isInteger(id)) {
    if (id === 1 || id === 3) return "not_started";
    if (id === 2) return "done";
    if (id === 4) return "returned";
    if (id === 5) return "in_process";
  }
  const l = getAssessmentStatusLabel(row).toLowerCase();
  if (isReturnedWaitingOnExecutor(row)) return "returned";
  if (isVerificationRequiredStatus(row, l)) return "in_process";
  if (l.includes("complete") || l.includes("done")) return "done";
  if (l.includes("progress") || l.includes("ongoing") || l.includes("in process")) return "not_started";
  if (l.includes("not started")) return "not_started";
  return "other";
}

export function buildCategoryMapsFromStatuses(statuses) {
  const executorMap = new Map();
  const verifierMap = new Map();
  if (!Array.isArray(statuses)) return { executorMap, verifierMap };

  for (const s of statuses) {
    const id = Number(s.assessment_status_id);
    if (Number.isNaN(id)) continue;
    const fake = {
      assessment_status_id: id,
      assessment_status_name: s.assessment_status_name,
    };
    executorMap.set(id, categorizeExecutorRow(fake));
    verifierMap.set(id, categorizeVerifierRow(fake));
  }
  return { executorMap, verifierMap };
}
