type CloudflareErrorItem = {
  message?: string;
};

type CloudflareApiEnvelope<T> = {
  success?: boolean;
  errors?: CloudflareErrorItem[];
  result?: T;
};

export type CloudflareCustomHostname = {
  id: string;
  hostname: string;
  status?: string | null;
  ownership_verification?: {
    name?: string | null;
    type?: string | null;
    value?: string | null;
  } | null;
  ssl?: {
    status?: string | null;
    validation_records?: Array<{
      txt_name?: string | null;
      txt_value?: string | null;
      cname?: string | null;
      cname_target?: string | null;
      status?: string | null;
    }> | null;
    dcv_delegation_records?: Array<{
      txt_name?: string | null;
      txt_value?: string | null;
      cname?: string | null;
      cname_target?: string | null;
      status?: string | null;
    }> | null;
  } | null;
};

function getConfig() {
  const token = process.env.CLOUDFLARE_API_TOKEN || "";
  const zoneId = process.env.CLOUDFLARE_ZONE_ID || "";
  const cnameTarget = (process.env.CLOUDFLARE_SAAS_CNAME_TARGET || "").trim().toLowerCase();
  return { token, zoneId, cnameTarget, enabled: Boolean(token && zoneId) };
}

async function requestCloudflare<T>(path: string, init: RequestInit): Promise<T> {
  const { token } = getConfig();
  if (!token) throw new Error("Cloudflare API token não configurado.");
  const response = await fetch(`https://api.cloudflare.com/client/v4${path}`, {
    ...init,
    headers: {
      authorization: `Bearer ${token}`,
      "content-type": "application/json",
      ...(init.headers || {}),
    },
    cache: "no-store",
  });
  const payload = (await response.json().catch(() => ({}))) as CloudflareApiEnvelope<T>;
  if (!response.ok || payload.success === false || !payload.result) {
    const cloudflareMessage = payload.errors?.[0]?.message || "Falha na API da Cloudflare.";
    throw new Error(cloudflareMessage);
  }
  return payload.result;
}

export function getCloudflareSaasConfig() {
  return getConfig();
}

export async function createCloudflareCustomHostname(hostname: string): Promise<CloudflareCustomHostname> {
  const { zoneId } = getConfig();
  if (!zoneId) throw new Error("Cloudflare zone não configurada.");
  return requestCloudflare<CloudflareCustomHostname>(`/zones/${zoneId}/custom_hostnames`, {
    method: "POST",
    body: JSON.stringify({
      hostname,
      ssl: {
        method: "txt",
        type: "dv",
      },
    }),
  });
}

export async function getCloudflareCustomHostname(customHostnameId: string): Promise<CloudflareCustomHostname> {
  const { zoneId } = getConfig();
  if (!zoneId) throw new Error("Cloudflare zone não configurada.");
  return requestCloudflare<CloudflareCustomHostname>(`/zones/${zoneId}/custom_hostnames/${customHostnameId}`, {
    method: "GET",
  });
}

export async function deleteCloudflareCustomHostname(customHostnameId: string): Promise<void> {
  const { zoneId } = getConfig();
  if (!zoneId) throw new Error("Cloudflare zone não configurada.");
  await requestCloudflare<CloudflareCustomHostname>(`/zones/${zoneId}/custom_hostnames/${customHostnameId}`, {
    method: "DELETE",
  });
}
