import { isOptionalApiRouteMissing } from "./apiErrorUtils";
import { isRecord, serverRequest } from "./serverConnection";

export interface WebPublicConfig {
  contactEmail?: string;
  contactPhone?: string;
  companyAddress?: string;
  icpRecord?: string;
}

function readString(config: Record<string, unknown>, keys: string[]): string | undefined {
  for (const key of keys) {
    const value = config[key];
    if (typeof value === "string" && value.trim()) return value.trim();
  }
  return undefined;
}

function normalizePublicConfig(raw: unknown): WebPublicConfig {
  const config = isRecord(raw) && isRecord(raw.config) ? raw.config : raw;
  if (!isRecord(config)) return {};

  return {
    contactEmail: readString(config, ["contactEmail", "contact_email", "supportEmail", "support_email"]),
    contactPhone: readString(config, ["contactPhone", "contact_phone", "supportPhone", "support_phone"]),
    companyAddress: readString(config, ["companyAddress", "company_address", "address"]),
    icpRecord: readString(config, ["icpRecord", "icp_record", "filingInfo", "filing_info"]),
  };
}

let cachedPublicConfig: WebPublicConfig | null = null;
let publicConfigRouteMissing = false;

export const publicConfigClient = {
  async get(): Promise<WebPublicConfig> {
    if (cachedPublicConfig) return cachedPublicConfig;
    if (publicConfigRouteMissing) return {};

    try {
      const payload = await serverRequest<unknown>("public/config/profile?name=web-public-config");
      cachedPublicConfig = normalizePublicConfig(payload);
      return cachedPublicConfig;
    } catch (error) {
      if (isOptionalApiRouteMissing(error)) {
        publicConfigRouteMissing = true;
        return {};
      }
      throw error;
    }
  },
};
