/**
 * Signal API helper — tries the backend, returns null on failure so the
 * app can fall back to client-side coverage calculation.
 */

const BACKEND_URL = import.meta.env.VITE_SIGNAL_BACKEND_URL ||
  "https://signal-api-production-91c2.up.railway.app";
// The frontend authenticates only with the signed-in user's Clerk token.
// It must never carry a service API key — that key would be baked into the
// public bundle and grant full backend access to anyone who views the source.

/**
 * Upload a CSV file to the backend scoring endpoint.
 * @param {File} file
 * @returns {Promise<object|null>} API response or null on failure
 */
export async function uploadToBackend(file, token = null) {
  const formData = new FormData();
  formData.append("file", file);
  const authHeader = token
    ? { "Authorization": `Bearer ${token}` }
    : {};
  try {
    const resp = await fetch(`${BACKEND_URL}/api/upload`, {
      method: "POST",
      headers: authHeader,
      body: formData,
    });
    if (!resp.ok) {
      const err = await resp.json().catch(() => ({}));
      throw new Error(err.detail?.message || `API error ${resp.status}`);
    }
    return resp.json();
  } catch (err) {
    throw err;
  }
}

/**
 * Export a work queue CSV from the backend.
 * @param {Array} records - scored RecordOut objects from the upload response
 * @param {string|null} batchId - batch_id from the upload response (for audit trail)
 */
export async function exportFromBackend(records, batchId = null, token = null) {
  const authHeader = token
    ? { "Authorization": `Bearer ${token}` }
    : {};
  try {
    const resp = await fetch(`${BACKEND_URL}/api/export`, {
      method: "POST",
      headers: { "Content-Type": "application/json", ...authHeader },
      body: JSON.stringify({ records, batch_id: batchId }),
    });
    if (!resp.ok) throw new Error(`API error ${resp.status}`);
    return resp.blob();
  } catch (err) {
    throw err;
  }
}

/**
 * Convert backend record shape to local record shape.
 */
export function apiRecordToLocal(r) {
  return {
    patient_id: r.patient_id,
    device_type: r.device_type,
    device_display: r.device_display,
    payer: r.payer,
    component: r.component,
    flag: r.flag,
    daysUntilEnd: r.days_until_coverage_end,
    days_until_coverage_end: r.days_until_coverage_end,
    daysUntilVisit: r.days_until_visit_due,
    days_until_visit_due: r.days_until_visit_due,
    priority: r.priority_score,
    priority_score: r.priority_score,
    coverageEndDate: r.coverage_end_date,
    coverage_end_date: r.coverage_end_date,
    nextVisitDueDate: r.next_visit_due_date,
    next_visit_due_date: r.next_visit_due_date,
    reason: r.reason || "",
    status_label: r.status_label,
    action: r.action,
    rule_version: r.rule_version,
    visit_date_confidence: r.visit_date_confidence || "estimated",
    is_transfer: r.is_transfer || false,
    doc_state: r.doc_state || null,
    cascade: r.cascade || [],
    order_number: r.order_number || null,
    hcpcs: r.hcpcs || null,
    recommended_next_step_code: r.recommended_next_step_code || "NO_ACTION_NEEDED",
    last_shipment_date: r.last_shipment_date || null,
    quantity: r.quantity || 1,
    csv_visit_date: r.csv_visit_date || null,
    csv_swo_status: r.csv_swo_status || null,
    csv_pecos_verified: r.csv_pecos_verified || null,
    csv_pa_status: r.csv_pa_status || null,
    csv_diagnosis_on_file: r.csv_diagnosis_on_file || null,
    csv_transfer_from: r.csv_transfer_from || null,
  };
}

/**
 * Confirm a qualifying visit date for a patient.
 * Returns the updated RecordOut from the backend.
 */
export async function confirmVisit(payload, token = null) {
  const authHeader = token
    ? { "Authorization": `Bearer ${token}` }
    : {};
  try {
    const res = await fetch(`${BACKEND_URL}/api/confirm-visit`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        ...authHeader,
      },
      body: JSON.stringify(payload),
    });

    if (!res.ok) {
      const err = await res.json().catch(() => ({}));
      throw new Error(err.detail || `HTTP ${res.status}`);
    }
    const raw = await res.json();
    // Normalize to local shape, preserving the P4 recompute payload (the
    // re-rolled patient) when the request echoed the patient's lines.
    const local = apiRecordToLocal(raw);
    if (raw.rollup_status !== undefined) local.rollup_status = raw.rollup_status;
    if (raw.lines) local.lines = raw.lines;
    return local;
  } catch (e) {
    throw e;
  }
}

/**
 * Export the work queue as one CSV row per device coverage line (P6,
 * granularity locked 2026-07-07). Falls through to the caller on failure.
 */
export async function exportLinesFromBackend(lines, batchId = null, token = null) {
  const authHeader = token
    ? { "Authorization": `Bearer ${token}` }
    : {};
  const resp = await fetch(`${BACKEND_URL}/api/export`, {
    method: "POST",
    headers: { "Content-Type": "application/json", ...authHeader },
    body: JSON.stringify({ records: [], lines, batch_id: batchId }),
  });
  if (!resp.ok) throw new Error(`API error ${resp.status}`);
  return resp.blob();
}

/**
 * Update SWO or PA status for a patient.
 * @param {string} patientId
 * @param {"swo"|"pa"} docType
 * @param {string} status - locked value for doc_type
 * @param {string|null} statusDate - YYYY-MM-DD, optional
 * @param {string|null} expiryDate - YYYY-MM-DD, optional
 * @param {string|null} token - Clerk JWT
 * @returns {Promise<{patient_id, doc_type, status, display}|null>}
 */
export async function updateDocStatus(patientId, docType, status, statusDate = null, expiryDate = null, token = null, deviceType = "", lines = null) {
  const authHeader = token
    ? { "Authorization": `Bearer ${token}` }
    : {};
  try {
    const resp = await fetch(`${BACKEND_URL}/api/doc-status`, {
      method: "PUT",
      headers: { "Content-Type": "application/json", ...authHeader },
      body: JSON.stringify({
        patient_id: patientId,
        doc_type: docType,
        status,
        // Device scope (P4): an SWO/PA update applies to this device's line
        // only, never to every device the patient has.
        ...(deviceType && { device_type: deviceType }),
        // Echo the patient's lines so the response carries the recomputed
        // {lines, rollup_status} from the same engine (P4 contract).
        ...(lines && { lines }),
        ...(statusDate && { status_date: statusDate }),
        ...(expiryDate && { expiry_date: expiryDate }),
      }),
    });
    if (!resp.ok) throw new Error(`API error ${resp.status}`);
    return resp.json();
  } catch (err) {
    throw err;
  }
}