import type {
  StatementAuditOption,
  StatementAuditSnapshot,
} from "@accessibit/types";
import {
  RECONNECT,
  SESSION_EXPIRED,
  SiteAdminApiError,
  type SiteAdminClient,
  type StatementPayload,
} from "../client";
import type { TrackerView } from "../tracker/types";
import type { WpAdminConfig } from "./config";
import type {
  FreeScanData,
  ScanResult,
  SummaryData,
} from "./accessibility/types";
import type { AccountDetails, ConnectionState } from "./setup/types";

/**
 * The bundle's backend: the plugin's `accessibit/v1` REST routes (ACC-404),
 * which check `manage_options` + the `wp_rest` nonce and proxy to audit-api's
 * public API (ACC-401) with the site-scoped key. The connected site is implied
 * by the key, so no route takes a site id; the `siteId`/`statementId` a save
 * body carries must be ignored or checked against it, and every `:id` route
 * must check that the statement belongs to the key's site.
 *
 * Routes, relative to `restRoot`:
 *
 *   GET  widget-settings                    → { settings, version }
 *   PUT  widget-settings                    { settings, expectedVersion }
 *                                           → { settings, version }
 *   GET  statement                          → { statement | null }
 *   POST statement                          StatementSaveInput → { statement }
 *   GET  statement/audit-options            → { options }
 *   GET  statement/audit-snapshot           → { snapshot | null }
 *   POST statement/preview                  { data, locale, primaryLocale,
 *                                             auditJobId } → { html }
 *   GET  statements/:id                     → { statement }
 *   POST statements/:id/generate            { endTemporary? } → { statement }
 *   GET  statements/:id/download/:artifact  → { url }
 *   GET    connection                       → ConnectionState
 *   DELETE connection                       → { outcome, connection }
 *   POST   connection/recheck               → { connection }
 *   POST   connection/verify-domain         → { connection }
 *   POST   connection/otp/request           { email } → { ok, email }
 *   POST   connection/otp/verify            { code, account? } → { connection,
 *                                             created }
 *   PUT    connection/widget                { enabled } → { connection }
 *   GET    scan/summary                     → the latest full audit's figures
 *   GET    scan/free                        → the free homepage scan
 *   POST   scan/free                        → { status }
 *   GET  tracker                            → TrackerView (ACC-412)
 *   PUT  tracker/schedule                   { enabled } → { enabled,
 *                                             nextRunAt }
 *
 * - `expectedVersion` is the version the page read: the GET's, then the one
 *   the last PUT or conflict returned; `null` means the site had no saved
 *   settings when the page loaded. A PUT whose
 *   `expectedVersion` is not the current one is refused with 409
 *   `{ error: { code: "version_conflict", message, current: { settings,
 *   version } } }`.
 * - `auditJobId` is the run the page's snapshot is based on, or null: the
 *   preview renders that run's verdict, or the no-audit variant.
 * - The download `url` is a short-lived https URL presigned with an
 *   attachment disposition.
 * - Statements carry no version: the last save wins, as in the dashboard.
 *
 * Errors are audit-api's `{ error: { code, message } }`, passed through; a
 * refused generation is `{ error: { code: "future_dates", message, fields } }`,
 * or 409 `temporary_active` while a temporary statement is served and the body
 * did not say `endTemporary: true`.
 * WordPress's own failures (nonce, capability) arrive as a `WP_Error`,
 * `{ code, message, data: { status } }`.
 */
export type WpClient = SiteAdminClient & {
  widget: SiteAdminClient["widget"] & {
    /** The stored settings and their version, before the settings page can
     * render. */
    load(): Promise<{ settings: unknown; version: number | null }>;
  };
  statements: SiteAdminClient["statements"] & {
    auditSnapshot(): Promise<StatementAuditSnapshot | null>;
  };
  /**
   * The Setup screen's: this install's connection. A refusal keeps the code
   * AccessiBit or the plugin gave it (`invalid_code`, `rate_limited` with
   * `details.retryAfterSeconds`, …), for the screen to word.
   */
  connection: {
    /** Emails a one-time code; answers the address as it was normalised. */
    requestCode(email: string): Promise<string>;
    /**
     * Redeems the code: the site is connected when this resolves. Refused
     * with `account_details_required` for an address without an account,
     * the same code is sent again with who to create one for.
     */
    verifyCode(
      code: string,
      account?: AccountDetails,
    ): Promise<ConnectionState>;
    recheck(): Promise<ConnectionState>;
    /**
     * Verifies the site's domain from this WordPress. Slow: AccessiBit reads
     * the site's public address before it answers.
     */
    verifyDomain(): Promise<ConnectionState>;
    /** Ends the connection; answers what became of the key. */
    disconnect(): Promise<string>;
    /** Turns the public widget on or off. */
    setWidget(enabled: boolean): Promise<ConnectionState>;
  };
  /**
   * The Accessibility screen's scans. A refusal resolves, as data: most are
   * states of the panel (never scanned, not verified, wait and retry).
   */
  scan: {
    summary(): Promise<ScanResult<SummaryData>>;
    freeScan(): Promise<ScanResult<FreeScanData>>;
    startFreeScan(): Promise<ScanResult<{ status?: string }>>;
  };
  /** The Tracker screen's (ACC-412): read-mostly, one switch. */
  tracker: {
    load(): Promise<TrackerView>;
    setMonitoring(enabled: boolean): Promise<void>;
  };
};

type Json = Record<string, unknown>;

/** Resolves `path` against the REST root, whichever permalink form it has. */
export function restUrl(restRoot: string, path: string): string {
  const url = new URL(restRoot, window.location.href);
  const route = url.searchParams.get("rest_route");
  if (route !== null) {
    url.searchParams.set("rest_route", `${route.replace(/\/$/, "")}/${path}`);
  } else {
    url.pathname = `${url.pathname.replace(/\/$/, "")}/${path}`;
  }
  return url.toString();
}

/** Either error shape → the error the pages show. */
export function toApiError(body: Json, status: number): SiteAdminApiError {
  const nested =
    body.error && typeof body.error === "object" ? (body.error as Json) : null;
  const message = (nested?.message ?? body.message) as unknown;
  const code = (nested?.code ?? body.code) as unknown;
  return new SiteAdminApiError(
    typeof message === "string" ? message : "",
    status,
    typeof code === "string" ? code : undefined,
    nested ?? body,
  );
}

/** The nonce went stale: the page has been open longer than WordPress allows. */
const EXPIRED_NONCE = "rest_cookie_invalid_nonce";

/**
 * The connection is gone: audit-api refused the key (revoked, or its site
 * deleted), the proxy found the site disconnected (another tab), or the key is
 * a company-wide one that may not write. Not WordPress's own 401, which means
 * the admin was signed out.
 */
const CONNECTION_GONE = new Set([
  "invalid_api_key",
  "accessibit_not_connected",
  "site_key_required",
]);

export function createWpClient(
  config: WpAdminConfig,
  copy: { sessionExpired: string; reconnect: string },
): WpClient {
  let nonce = config.nonce;
  let refreshing: Promise<boolean> | null = null;

  /**
   * A fresh `wp_rest` nonce from core, for an admin who signed in again with
   * the page open: theirs died with the old session, and reloading would lose
   * the edits they signed in to keep. One request however many calls ask.
   */
  function refreshNonce(): Promise<boolean> {
    const url = config.nonceUrl;
    if (!url) return Promise.resolve(false);
    refreshing ??= (async () => {
      try {
        const res = await fetch(url, { credentials: "same-origin" });
        const fresh = (await res.text()).trim();
        // "0" when signed out: nothing to retry with.
        if (!res.ok || !/^[0-9a-f]{10}$/i.test(fresh)) return false;
        nonce = fresh;
        return true;
      } catch {
        return false;
      }
    })().finally(() => {
      refreshing = null;
    });
    return refreshing;
  }

  async function call(
    method: "GET" | "POST" | "PUT" | "DELETE",
    path: string,
    body?: unknown,
    signal?: AbortSignal,
    retried = false,
  ): Promise<Json> {
    const res = await fetch(restUrl(config.restRoot, path), {
      method,
      signal,
      credentials: "same-origin",
      headers: {
        "X-WP-Nonce": nonce,
        ...(body === undefined ? {} : { "Content-Type": "application/json" }),
      },
      body: body === undefined ? undefined : JSON.stringify(body),
    });
    const parsed: unknown = await res.json().catch(() => undefined);
    const json: Json =
      parsed && typeof parsed === "object" && !Array.isArray(parsed)
        ? (parsed as Json)
        : {};
    // A 2xx that is not a JSON object (a PHP notice printed before it, say)
    // must not read as "nothing saved": the page would offer defaults or an
    // empty statement, and saving them would overwrite what is stored.
    if (res.ok && json !== parsed) throw new SiteAdminApiError("", res.status);
    if (!res.ok) {
      const err = toApiError(json, res.status);
      if (err.code === EXPIRED_NONCE && !retried && (await refreshNonce())) {
        return call(method, path, body, signal, true);
      }
      if (err.code === EXPIRED_NONCE) {
        throw new SiteAdminApiError(
          copy.sessionExpired,
          err.status,
          SESSION_EXPIRED,
          err.details,
        );
      }
      if (err.code && CONNECTION_GONE.has(err.code)) {
        throw new SiteAdminApiError(
          copy.reconnect,
          err.status,
          RECONNECT,
          err.details,
        );
      }
      // The pages word every other failure themselves, by its code or status:
      // the server's sentence is English, for whoever reads its logs, and
      // stays in `details.message`.
      throw new SiteAdminApiError("", err.status, err.code, err.details);
    }
    return json;
  }

  // `version: null` means nothing is stored (any more): the next save creates.
  const versionOf = (json: Json): number | null =>
    typeof json.version === "number" ? json.version : null;

  const connectionOf = (json: Json): ConnectionState => {
    const connection = json.connection;
    if (!connection || typeof connection !== "object") {
      throw new SiteAdminApiError("");
    }
    return connection as ConnectionState;
  };

  /** A scan call, with its refusal as data (`ScanResult`). */
  async function scanCall<T>(
    method: "GET" | "POST",
    path: string,
  ): Promise<ScanResult<T>> {
    try {
      return { ok: true, data: (await call(method, path)) as T };
    } catch (err) {
      // The browser never reached WordPress.
      if (!(err instanceof SiteAdminApiError)) {
        return { ok: false, code: "network" };
      }
      // WordPress no longer accepts this page's requests: the nonce went
      // stale, or the administrator was signed out (its own `rest_*` codes).
      if (err.code === SESSION_EXPIRED || err.code?.startsWith("rest_")) {
        return { ok: false, code: "session" };
      }
      // An answer that is not the plugin's JSON (a PHP notice printed
      // before it, a proxy's page): AccessiBit was not reached.
      if (!err.code && (err.status ?? 0) < 400) {
        return { ok: false, code: "network" };
      }
      const wait = err.details?.retryAfterMs;
      return {
        ok: false,
        code: err.code ?? "request_failed",
        ...(typeof wait === "number" ? { retryAfterMs: wait } : {}),
      };
    }
  }

  return {
    scan: {
      summary: () => scanCall("GET", "scan/summary"),
      freeScan: () => scanCall("GET", "scan/free"),
      startFreeScan: () => scanCall("POST", "scan/free"),
    },
    connection: {
      async setWidget(enabled) {
        return connectionOf(
          await call("PUT", "connection/widget", { enabled }),
        );
      },
      async requestCode(email) {
        const json = await call("POST", "connection/otp/request", { email });
        return typeof json.email === "string" ? json.email : email;
      },
      async verifyCode(code, account) {
        return connectionOf(
          await call("POST", "connection/otp/verify", {
            code,
            ...(account ? { account } : {}),
          }),
        );
      },
      async recheck() {
        return connectionOf(await call("POST", "connection/recheck"));
      },
      async verifyDomain() {
        return connectionOf(await call("POST", "connection/verify-domain"));
      },
      async disconnect() {
        const json = await call("DELETE", "connection");
        return typeof json.outcome === "string" ? json.outcome : "none";
      },
    },
    tracker: {
      async load() {
        const json = await call("GET", "tracker");
        // Anything but an explicit `active: true` is a site without the
        // Tracker: the screen then offers to activate it, nothing more.
        if (json.active !== true) return { active: false };
        const runs = Array.isArray(json.runs) ? json.runs : [];
        return {
          ...(json as unknown as TrackerView & { active: true }),
          runs,
          totalRuns:
            typeof json.totalRuns === "number" ? json.totalRuns : runs.length,
        };
      },
      async setMonitoring(enabled) {
        await call("PUT", "tracker/schedule", { enabled });
      },
    },
    widget: {
      async load() {
        const json = await call("GET", "widget-settings");
        return { settings: json.settings, version: versionOf(json) };
      },
      async saveSettings(_siteId, settings, expectedVersion) {
        try {
          const json = await call("PUT", "widget-settings", {
            settings,
            expectedVersion,
          });
          // 202: stored, but not on the CDN yet. Saying "published on your
          // site" would be untrue until the republish sweep runs, so it is the
          // dashboard's `publish_failed`, carrying the version that was stored.
          if (json.published === false) {
            throw new SiteAdminApiError("", 202, "publish_failed", {
              version: typeof json.version === "number" ? json.version : null,
            });
          }
          return {
            settings: json.settings,
            version:
              typeof json.version === "number" ? json.version : undefined,
          };
        } catch (err) {
          if (
            !(err instanceof SiteAdminApiError) ||
            err.code !== "version_conflict"
          ) {
            throw err;
          }
          // The page needs what is stored now to offer it, and its version
          // for the next save: a deliberate overwrite, not another 409. A
          // body without it is answered by reading it; if that read fails,
          // its own error (an expired session, say) is the one to show.
          let current = err.details?.current as Json | undefined;
          if (current?.settings === undefined) {
            current = await call("GET", "widget-settings");
          }
          throw new SiteAdminApiError(err.message, err.status, err.code, {
            ...err.details,
            current: {
              settings: current.settings,
              version: versionOf(current),
            },
          });
        }
      },
    },
    statements: {
      async getForSite(_siteId, options) {
        const json = await call("GET", "statement", undefined, options?.signal);
        return (json.statement as StatementPayload | null) ?? null;
      },
      async get(id) {
        const json = await call("GET", `statements/${encodeURIComponent(id)}`);
        return (json.statement as StatementPayload | null) ?? null;
      },
      async save(input) {
        const json = await call("POST", "statement", input);
        if (!json.statement) throw new SiteAdminApiError("");
        return json.statement as StatementPayload;
      },
      async generate(id, options) {
        try {
          const json = await call(
            "POST",
            `statements/${encodeURIComponent(id)}/generate`,
            options?.endTemporary === true ? { endTemporary: true } : undefined,
          );
          return {
            ok: true,
            statement: (json.statement as StatementPayload | null) ?? null,
          };
        } catch (err) {
          if (
            err instanceof SiteAdminApiError &&
            err.status === 409 &&
            err.code === "temporary_active"
          ) {
            return { ok: false, code: "temporary_active" };
          }
          if (err instanceof SiteAdminApiError && err.code === "future_dates") {
            const fields = err.details?.fields;
            return {
              ok: false,
              code: "future_dates",
              fields: Array.isArray(fields) ? fields.map(String) : [],
              message:
                typeof err.details?.message === "string"
                  ? err.details.message
                  : "",
            };
          }
          throw err;
        }
      },
      async download(id, artifact) {
        const json = await call(
          "GET",
          `statements/${encodeURIComponent(id)}/download/${artifact}`,
        );
        // The page navigates to it, so anything but https (`javascript:`
        // above all) is refused rather than followed.
        const url = typeof json.url === "string" ? json.url : "";
        let protocol = "";
        try {
          protocol = new URL(url).protocol;
        } catch {
          // not a URL
        }
        if (protocol !== "https:") throw new SiteAdminApiError("");
        return { url };
      },
      async auditOptions() {
        const json = await call("GET", "statement/audit-options");
        return (json.options as StatementAuditOption[] | undefined) ?? [];
      },
      async auditSnapshot() {
        const json = await call("GET", "statement/audit-snapshot");
        return (json.snapshot as StatementAuditSnapshot | null) ?? null;
      },
      publicUrl(id) {
        return `${config.apiOrigin.replace(/\/$/, "")}/api/public/statements/${encodeURIComponent(id)}`;
      },
      async loadPreview({ data, locale, primaryLocale, audit }) {
        const json = await call("POST", "statement/preview", {
          data,
          locale,
          primaryLocale,
          auditJobId: audit?.basedOn.jobId ?? null,
        });
        return typeof json.html === "string" ? json.html : "";
      },
    },
  };
}
