import type { AdapterResult } from "../types";
import {
  commercialDelete,
  commercialGet,
  commercialPatch,
  commercialPost,
  extractItems,
  failResult,
  listResult,
} from "../adapters/http";
import type { CommercialAdminResourceDef } from "../admin/resources";

export type RegistryRecord = Record<string, unknown>;

export async function listAdminRegistry(
  resource: CommercialAdminResourceDef,
  tenantId?: string | null
): Promise<AdapterResult<RegistryRecord[]>> {
  if (resource.requiresTenant && !tenantId) {
    return {
      availability: "empty",
      data: [],
      source: "admin.tenant-selection",
      message: "برای مشاهده این بخش، ابتدا یک فضای کاری انتخاب کنید.",
    };
  }
  if (resource.key === "entitlements") {
    return {
      availability: "empty",
      data: [],
      source: "admin.entitlements",
      message: "سطوح دسترسی در صفحه اشتراک و محصولات هر فضای کاری نمایش داده می‌شود.",
    };
  }

  const query = tenantId ? `tenant_id=${encodeURIComponent(tenantId)}` : "";
  const path =
    resource.key === "subscriptions"
      ? `/api/v1/commercial/dashboard?${query}`
      : resource.key === "activation-logs"
        ? `/api/v1/commercial/activation?${query}`
        : `${resource.listPath}${query ? `?${query}` : ""}`;
  const res = await commercialGet<unknown>(path);
  if (!res.ok) {
    return failResult(res.availability, res.message, []);
  }
  if (resource.key === "subscriptions") {
    const subscription = (res.data as { subscription?: RegistryRecord | null }).subscription;
    return listResult(
      subscription ? [subscription] : [],
      "admin.subscriptions",
      "اشتراکی ثبت نشده است."
    );
  }
  if (resource.key === "activation-logs") {
    const pipeline = (res.data as { pipeline?: RegistryRecord | null }).pipeline;
    const item = pipeline || (res.data as RegistryRecord);
    return listResult(
      item && Object.keys(item).length ? [item] : [],
      "admin.activation",
      "فعال‌سازی ثبت نشده است."
    );
  }
  const items = extractItems<RegistryRecord>(res.data, resource.envelopeKeys);
  return listResult(items, `admin.${resource.key}`, "موردی در رجیستری نیست");
}

export async function createAdminRegistryItem(
  resource: CommercialAdminResourceDef,
  body: RegistryRecord
): Promise<{ ok: true; data: RegistryRecord } | { ok: false; message: string }> {
  const res = await commercialPost<RegistryRecord>(resource.createPath, body);
  if (!res.ok) return { ok: false, message: res.message };
  return { ok: true, data: res.data };
}

export async function updateAdminRegistryItem(
  resource: CommercialAdminResourceDef,
  code: string,
  body: RegistryRecord
): Promise<{ ok: true; data: RegistryRecord } | { ok: false; message: string }> {
  const path = `${resource.listPath}/${encodeURIComponent(code)}`;
  const patch = await commercialPatch<RegistryRecord>(path, body);
  if (patch.ok) return { ok: true, data: patch.data };
  return { ok: false, message: patch.message };
}

export async function deleteAdminRegistryItem(
  resource: CommercialAdminResourceDef,
  code: string
): Promise<{ ok: true } | { ok: false; message: string }> {
  const path = `${resource.listPath}/${encodeURIComponent(code)}`;
  const res = await commercialDelete(path);
  if (!res.ok) return { ok: false, message: res.message };
  return { ok: true };
}

export async function simulateRecommendations(answers: Record<string, unknown>) {
  return commercialPost<unknown>("/api/v1/commercial/recommendations", {
    answers,
    version: "recommendation.v1",
  });
}
