import type { AdapterResult, SetupChecklistItem } from "../types";
import { commercialGet, extractItems, failResult, listResult } from "./http";

export interface ActivationStep {
  step_key: string;
  label?: string | null;
  status?: string | null;
  href?: string | null;
  metadata?: Record<string, unknown>;
}

export interface ActivationPipeline {
  correlation_id?: string;
  status?: string | null;
  steps: ActivationStep[];
  completion_percent?: number | null;
}

export async function loadActivationPipeline(
  tenantId: string
): Promise<AdapterResult<ActivationPipeline | null>> {
  const res = await commercialGet<ActivationPipeline | { pipeline?: ActivationPipeline }>(
    `/api/v1/commercial/activation?tenant_id=${encodeURIComponent(tenantId)}`
  );
  if (!res.ok) {
    return failResult(res.availability, res.message || "پایپ‌لاین فعال‌سازی در دسترس نیست", null);
  }
  const pipeline =
    (res.data as { pipeline?: ActivationPipeline }).pipeline || (res.data as ActivationPipeline);
  if (!pipeline?.steps?.length) {
    return {
      availability: "empty",
      data: { steps: [], completion_percent: 0 },
      source: "commercial.activation",
      message: "گامی ثبت نشده",
    };
  }
  return { availability: "ready", data: pipeline, source: "commercial.activation" };
}

export async function loadSetupChecklistFromApi(
  tenantId: string
): Promise<AdapterResult<SetupChecklistItem[]>> {
  const res = await commercialGet<unknown>(
    `/api/v1/commercial/checklist?tenant_id=${encodeURIComponent(tenantId)}`
  );
  if (!res.ok) {
    return failResult(res.availability, res.message || "چک‌لیست در دسترس نیست", []);
  }
  const items = extractItems<SetupChecklistItem>(res.data, ["items", "checklist", "steps"]);
  const percent = (res.data as { completion_percent?: number })?.completion_percent;
  const normalized = items.map((i) => ({
    ...i,
    id: i.id || i.product_code || i.label,
  }));
  const result = listResult(normalized, "commercial.checklist", "چک‌لیست خالی است");
  if (percent != null) {
    (result as AdapterResult<SetupChecklistItem[]> & { completion_percent?: number }).completion_percent =
      percent;
  }
  return result;
}
