/**
 * Connector HTTP client. Connector rules (BRD §10): per-connector backoff on rate limits, idempotency keys,
 * and every request/response summary logged to the connection-health view (INT-002).
 */
import { schema } from "@/db";
import type { Ctx } from "@/lib/auth";
import { sleep } from "@/lib/util";

export class ProviderError extends Error {
  constructor(public provider: string, public status: number, message: string, public body?: unknown) {
    super(message);
  }
}

export async function logIntegration(ctx: Pick<Ctx, "db" | "workspace">, provider: string, integrationId: string | null, direction: "in" | "out", operation: string, status: "ok" | "error", summary: string) {
  await ctx.db.insert(schema.integrationLogs).values({ workspaceId: ctx.workspace.id, provider, integrationId, direction, operation, status, summary: summary.slice(0, 1000) }).catch(() => {});
}

export async function providerFetch<T = unknown>(
  ctx: Pick<Ctx, "db" | "workspace">,
  provider: string,
  integrationId: string | null,
  operation: string,
  url: string,
  init: RequestInit & { retries?: number; idempotencyKey?: string } = {},
): Promise<T> {
  const retries = init.retries ?? 3;
  let attempt = 0;
  for (;;) {
    attempt++;
    const headers = new Headers(init.headers);
    if (init.idempotencyKey) headers.set("Idempotency-Key", init.idempotencyKey);
    let res: Response;
    try {
      res = await fetch(url, { ...init, headers, signal: AbortSignal.timeout(20000) });
    } catch (e) {
      if (attempt <= retries) {
        await sleep(2 ** attempt * 400);
        continue;
      }
      await logIntegration(ctx, provider, integrationId, "out", operation, "error", `Network error: ${(e as Error).message}`);
      throw new ProviderError(provider, 0, `Network error calling ${provider}`);
    }
    const text = await res.text();
    let json: unknown = text;
    try {
      json = text ? JSON.parse(text) : {};
    } catch {
      /* non-JSON */
    }
    if ((res.status === 429 || res.status >= 500) && attempt <= retries) {
      const ra = Number(res.headers.get("retry-after"));
      await sleep(ra ? ra * 1000 : 2 ** attempt * 500);
      continue;
    }
    if (!res.ok) {
      const msg = extractError(json) ?? `${res.status} ${res.statusText}`;
      await logIntegration(ctx, provider, integrationId, "out", operation, "error", `${res.status}: ${msg}`);
      throw new ProviderError(provider, res.status, msg, json);
    }
    await logIntegration(ctx, provider, integrationId, "out", operation, "ok", `${res.status} ${operation}`);
    return json as T;
  }
}

function extractError(j: unknown): string | null {
  if (!j || typeof j !== "object") return typeof j === "string" ? j.slice(0, 300) : null;
  const o = j as Record<string, any>;
  return o.error?.message ?? o.error_description ?? o.message ?? o.errors?.[0]?.message ?? (typeof o.error === "string" ? o.error : null);
}
