// What the free homepage scan panel shows for each answer the plugin can
// give. A port of the plugin's own `admin/js/free-scan.js`, which still draws
// the PHP view when the app does not run: the two must say every state the
// same way, and each branch here keeps that script's reason for existing.
//
// It renders what the service returns. The "first few issues plus the total"
// limit is the service's, and deliberately not repeated here: a plugin that
// received the full list and hid part of it would be locking functionality
// it shipped, which wordpress.org forbids.
import type {
  FreeScanData,
  FreeScanIssue,
  FreeScanStrings,
  ScanResult,
} from "./types";

export const POLL_INTERVAL_MS = 4000;
export const MAX_POLLS = 45;
/**
 * Longest wait the screen sits through before the retry comes back by
 * itself. The backoff is ten minutes; beyond this the reader is told to come
 * back rather than left with a timer of hours.
 */
export const MAX_WAIT_MS = 15 * 60000;

/** The connection is broken, which is not a failed scan. */
const RECONNECT_CODES = new Set([
  "invalid_api_key",
  "account_not_found",
  "forbidden",
  "site_not_found",
  // The plugin's own: not connected, or another tab disconnected.
  "accessibit_not_connected",
  "reconnect_required",
]);
/** The request never reached AccessiBit: a firewall on this site, usually. */
const BLOCKED = "network_error";
const NOT_VERIFIED = "site_not_verified";
/** "Ask again shortly": the scan itself may be fine. */
const TRANSIENT_CODES = new Set([
  "rate_limited",
  "scanner_busy",
  "service_unavailable",
  "internal_error",
  "request_failed",
]);
const RETRY_TOO_SOON = "free_scan_retry_too_soon";
/** Recorded failures where no scan ran: "we could not scan" would be untrue. */
const NEVER_RAN_CODES = new Set(["SCANNER_BUSY"]);

export interface FreeScanCta {
  /**
   * `enabled` offers another attempt; `spent` and `waiting` show the control
   * unavailable, with why beside it. Absent: no retry at all.
   */
  retry?: "enabled" | "spent" | "waiting";
  /** With `waiting`: how long until the retry comes back. */
  waitMs?: number;
  /** Whether this state has earned the link to the plans: a result has, a
   * failure has not. */
  buy?: boolean;
}

export interface FreeScanPanel {
  message: string;
  issues: FreeScanIssue[];
  /** The language of the issue messages, for `lang`. */
  lang?: string;
  cta: FreeScanCta;
  /** What the screen does next by itself: read again, or claim the scan. */
  next?: "poll" | "start";
}

const fill = (template: string, value: string | number) =>
  String(template).replace("%s", String(value));

/** A wait in whole minutes, rounded up, floored at one; 0 for none. */
export function waitMinutes(ms: unknown): number {
  const n = Number(ms);
  if (!Number.isFinite(n) || n <= 0) return 0;
  return Math.max(1, Math.ceil(n / 60000));
}

/** The wait in a sentence, with no counted noun to get wrong. */
function waitPhrase(ms: unknown, t: FreeScanStrings): string {
  const minutes = waitMinutes(ms);
  if (minutes <= 0) return "";
  if (minutes === 1) return t.retryAfterOne || t.retryLater || "";
  return fill(t.retryAfter, minutes);
}

/** "Not yet", with the length of the wait whenever the service sent one. */
function retryTooSoon(waitMs: unknown, t: FreeScanStrings): FreeScanPanel {
  const minutes = waitMinutes(waitMs);
  return {
    message: waitPhrase(waitMs, t) || t.retryLater,
    issues: [],
    // Without a wait to wait out the control is offered: a press that may
    // be refused again beats one that cannot happen.
    cta:
      minutes > 0
        ? { retry: "waiting", waitMs: Number(waitMs) }
        : { retry: "enabled" },
  };
}

function scannedOn(
  data: FreeScanData,
  t: FreeScanStrings,
  formatDate: (date: Date) => string,
): string {
  if (!data.scannedAt || !t.scannedOn) return "";
  const when = new Date(data.scannedAt);
  if (Number.isNaN(when.getTime())) return "";
  return ` ${fill(t.scannedOn, formatDate(when))}`;
}

function completed(
  data: FreeScanData,
  t: FreeScanStrings,
  formatDate: (date: Date) => string,
): FreeScanPanel {
  const total = Number(data.totalIssues) || 0;
  const issues = Array.isArray(data.issues) ? data.issues : [];
  if (total === 0) {
    return {
      message: t.clean + scannedOn(data, t, formatDate),
      issues: [],
      cta: { buy: true },
    };
  }
  // A label and a count, with no pluralised noun; then the date, since the
  // scan is once per domain and a result without one reads as current.
  let headline = fill(t.issuesFound, total) + scannedOn(data, t, formatDate);
  // Last, because it ends in a colon that introduces the list. The total
  // counts instances and the list is one line per distinct rule, capped
  // after de-duplication: a list shorter than the cap is complete.
  if (issues.length > 0) {
    const limit = Number(data.previewLimit) || 0;
    headline += ` ${
      limit > 0 && issues.length >= limit
        ? fill(t.showingSome, issues.length)
        : t.showingAll
    }`;
  }
  return { message: headline, issues, lang: data.lang, cta: { buy: true } };
}

/** A failed scan, in terms of what went wrong. */
function failed(data: FreeScanData, t: FreeScanStrings): FreeScanPanel {
  const reason = data.reason;
  const detail = reason ? t.failureCodes[reason] : undefined;
  // Past the attempt ceiling the retry is shown unavailable, not removed.
  const exhausted = data.retryable === false;
  // Attempts left, but the backoff has not elapsed.
  const waiting = !exhausted && waitMinutes(data.retryAfterMs) > 0;
  const neverRan = !!reason && NEVER_RAN_CODES.has(reason) && !!detail;
  const lead = exhausted ? t.exhausted : neverRan ? "" : t.failed;
  let tail = detail ? (lead ? " " : "") + detail : "";
  if (!exhausted && !detail) tail = ` ${t.supportHint}`;
  // The wait goes last, after what went wrong.
  if (waiting) tail += ` ${waitPhrase(data.retryAfterMs, t)}`;
  return {
    message: lead + tail,
    issues: [],
    cta: {
      retry: exhausted ? "spent" : waiting ? "waiting" : "enabled",
      ...(waiting ? { waitMs: Number(data.retryAfterMs) } : {}),
    },
  };
}

/** A refusal both calls can get, or null when it is the caller's to word. */
function refusal(
  result: { code: string; retryAfterMs?: number },
  t: FreeScanStrings,
): FreeScanPanel | null {
  const { code } = result;
  const bare = (message: string): FreeScanPanel => ({
    message,
    issues: [],
    cta: {},
  });
  if (code === "session") return bare(t.session);
  if (code === NOT_VERIFIED) return bare(t.notVerified);
  if (RECONNECT_CODES.has(code)) return bare(t.reconnect);
  // The browser never reached WordPress: nothing to say about AccessiBit.
  if (code === "network") {
    return { message: t.network, issues: [], cta: { retry: "enabled" } };
  }
  // A retry is still offered: unblocking the firewall is something the
  // administrator can do, and then the very next request works.
  if (code === BLOCKED) {
    return { message: t.blocked, issues: [], cta: { retry: "enabled" } };
  }
  if (code === RETRY_TOO_SOON) return retryTooSoon(result.retryAfterMs, t);
  if (TRANSIENT_CODES.has(code)) {
    // A transient refusal that says how long is the waiting state, not "busy".
    if (waitMinutes(result.retryAfterMs) > 0) {
      return retryTooSoon(result.retryAfterMs, t);
    }
    return { message: t.busy, issues: [], cta: { retry: "enabled" } };
  }
  return null;
}

const unexplained = (t: FreeScanStrings): FreeScanPanel => ({
  message: `${t.failed} ${t.supportHint}`,
  issues: [],
  cta: { retry: "enabled" },
});

/**
 * The panel for a read of the scan. `attempts` is how many reads this poll
 * has made, so a scan slower than the page is willing to wait is told apart
 * from a failed one.
 */
export function panelForRead(
  result: ScanResult<FreeScanData>,
  attempts: number,
  t: FreeScanStrings,
  formatDate: (date: Date) => string,
): FreeScanPanel {
  if (result.ok === false) {
    // The one expected refusal on a first visit: this domain has never had
    // its free scan. Claim it.
    if (result.code === "free_scan_not_found") {
      return { message: t.starting, issues: [], cta: {}, next: "start" };
    }
    return refusal(result, t) ?? unexplained(t);
  }
  const data = result.data;
  if (!data || !data.status) {
    return { message: t.network, issues: [], cta: {} };
  }
  if (data.status === "completed") return completed(data, t, formatDate);
  if (data.status === "failed") return failed(data, t);
  // Still running. Past the last poll it is not a failure: the service
  // still says running, so reloading is the honest instruction.
  if (attempts >= MAX_POLLS) {
    return { message: t.slow, issues: [], cta: {} };
  }
  return { message: t.scanning, issues: [], cta: {}, next: "poll" };
}

/** The panel for the answer to starting the scan. */
export function panelForStart(
  result: ScanResult<{ status?: string }>,
  t: FreeScanStrings,
): FreeScanPanel {
  if (result.ok !== false) {
    // Started here, or by another install of the same domain: either way
    // the result is read next.
    return { message: t.scanning, issues: [], cta: {}, next: "poll" };
  }
  if (result.code === "free_scan_exhausted") {
    return { message: t.exhausted, issues: [], cta: { retry: "spent" } };
  }
  return refusal(result, t) ?? unexplained(t);
}
