import type {
  StatementAuditOption,
  StatementAuditSnapshot,
  StatementData,
  StatementLocale,
  StatementLocalizedFields,
  TemporaryColumns,
  WidgetSettings,
} from "@accessibit/types";

/**
 * Everything the pages need from a backend: the dashboard's `/api/*` routes or
 * the plugin's `accessibit/v1` routes. Failures throw `SiteAdminApiError` with
 * a message fit to show, or "" to fall back to the page's own copy.
 */
export interface SiteAdminClient {
  widget: {
    /**
     * Saves over `expectedVersion`, the version the page read (`null`: none
     * was stored). Resolves with the settings as stored (the server sanitizes
     * too) and their version, either undefined when the answer carries none:
     * what was sent is then what is stored. Throws a `SiteAdminApiError` with
     * the answer's status, or a `version_conflict` whose `details.current` is
     * `{ settings, version }` as stored now.
     */
    saveSettings(
      siteId: string,
      settings: WidgetSettings,
      expectedVersion: number | null | undefined,
    ): Promise<WidgetSaveAnswer>;
  };
  statements: {
    /** The site's statement, or null when none was ever saved. */
    getForSite(
      siteId: string,
      options?: { signal?: AbortSignal },
    ): Promise<StatementPayload | null>;
    /** One statement by id — what the page polls while generation runs. */
    get(id: string): Promise<StatementPayload | null>;
    /** Creates or updates the draft. */
    save(input: StatementSaveInput): Promise<StatementPayload>;
    /**
     * Queues generation of every published language. `endTemporary` is the
     * customer's yes to ending an active temporary statement, which the
     * server otherwise refuses to (`temporary_active`).
     */
    generate(
      id: string,
      options?: { endTemporary?: boolean },
    ): Promise<StatementGenerateResult>;
    /** The file, or a short-lived URL that serves it as an attachment. */
    download(
      id: string,
      artifact: "html" | "pdf",
    ): Promise<{ blob: Blob; filename: string | null } | { url: string }>;
    /** The audits the statement may declare (ACC-388's picker). */
    auditOptions(siteId: string): Promise<StatementAuditOption[]>;
    /** audit-api's public entry point, which negotiates the language. */
    publicUrl(id: string): string;
    /**
     * The live preview, as generation will write it. Implement one: the
     * WordPress bundle may not carry the templates, so it asks the server.
     */
    renderPreview?(input: StatementPreviewInput): string;
    loadPreview?(input: StatementPreviewInput): Promise<string>;
    /**
     * Publishes the temporary statement (ACC-504) from the SAVED row, until
     * `releaseDate`. A refusal resolves with the server's code, which the
     * page words. Unset where the host has no temporary statement to offer.
     */
    publishTemporary?(
      id: string,
      releaseDate: string,
    ): Promise<{ ok: true } | { ok: false; code: string }>;
    /** The temporary document, as its publication will write it. */
    renderTemporaryPreview?(input: TemporaryPreviewInput): string;
  };
}

export interface StatementPreviewInput {
  data: StatementData;
  locale: StatementLocale;
  primaryLocale: StatementLocale;
  /** The verdict the document declares; null renders the no-audit variant. */
  audit: StatementAuditSnapshot | null;
}

export interface TemporaryPreviewInput {
  /** The form as it would be saved: the columns the document prints. */
  columns: TemporaryColumns;
  /** The site's own address, as generation reads it. */
  siteUrl: string;
  locale: StatementLocale;
  draftedOn: string;
  releaseDate: string;
}

export type StatementGenerateResult =
  | { ok: true; statement: StatementPayload | null }
  /** Dates the server considers in the future; `message` is its own. */
  | { ok: false; code: "future_dates"; fields: string[]; message: string }
  /**
   * A temporary statement is active, which generating would end: asked for
   * without `endTemporary` (one published after the page was read).
   */
  | { ok: false; code: "temporary_active" };

export interface WidgetSaveAnswer {
  settings?: unknown;
  version?: number;
}

/**
 * The code of an error that means the user has to sign in again, whatever
 * status the backend answered it with (WordPress says 403 for a stale nonce).
 */
export const SESSION_EXPIRED = "session_expired";

/**
 * The code of an error that means the site's connection to AccessiBit is gone
 * (its key revoked, or the site disconnected): only reconnecting fixes it.
 */
export const RECONNECT = "reconnect_required";

export class SiteAdminApiError extends Error {
  constructor(
    message: string,
    readonly status?: number,
    readonly code?: string,
    /** The rest of the error body, for codes that carry more (`fields`). */
    readonly details?: Record<string, unknown>,
  ) {
    super(message);
    this.name = "SiteAdminApiError";
  }
}

/** The page has to be reloaded: no retry from it can work. */
export const isSessionExpired = (err: unknown): boolean =>
  err instanceof SiteAdminApiError && err.code === SESSION_EXPIRED;

/** One row of `Statement.files` — one generated language. */
export interface StatementFilePayload {
  locale?: string | null;
  generatedAt?: string | null;
  publicHtmlUrl?: string | null;
  publicPdfUrl?: string | null;
}

/** One row of `Statement.contents` — one language's free text. */
export interface StatementContentPayload {
  locale?: string | null;
  measuresTaken?: string | null;
  knownLimitations?: string | null;
  additionalNotes?: string | null;
  lawNonComplianceReason?: string | null;
  disproportionateBurdenReason?: string | null;
  outOfScopeContentReason?: string | null;
}

/** The statement row and its relations; dates arrive as ISO strings. */
export interface StatementPayload {
  id: string;
  /** The document's own language, as stored on the statement row. */
  locale?: string;
  status?: string;
  /** When the row was last written: every save moves it. */
  updatedAt?: string | null;
  companyName?: string | null;
  firstName?: string | null;
  lastName?: string | null;
  feedbackEmail?: string | null;
  entityType?: string | null;
  siteCMS?: string | null;
  sitePublicationDate?: string | null;
  conformanceLevel?: string | null;
  statementDate?: string | null;
  /** NULL means "not declared"; 0 is a declared zero. */
  employeesWithDisabilities?: number | null;
  workstationsForDisabilities?: number | null;
  includePdfDisclaimer?: boolean | null;
  lawNonCompliance?: boolean | null;
  disproportionateBurden?: boolean | null;
  outOfScopeContent?: boolean | null;
  usabilityTestsPerformed?: boolean | null;
  /** One row per language the customer has written into. */
  contents?: StatementContentPayload[];
  /** One entry per generated language. */
  files?: StatementFilePayload[];
}

/** Every column, on every save: an omitted field is overwritten upstream. */
export interface StatementSaveInput {
  statementId: string | null;
  siteId: string;
  /** The document's primary language — the generator's fallback. */
  locale: StatementLocale;
  /** The pinned audit, or null for "the latest". */
  auditJobId: string | null;
  companyName: string;
  firstName: string;
  lastName: string;
  feedbackEmail: string;
  entityType: "public" | "private";
  siteCMS: string;
  sitePublicationDate: string;
  statementDate: string;
  conformanceLevel: string;
  employeesWithDisabilities: string;
  workstationsForDisabilities: string;
  includePdfDisclaimer: boolean;
  lawNonCompliance: boolean;
  disproportionateBurden: boolean;
  outOfScopeContent: boolean;
  usabilityTestsPerformed: boolean;
  contents: Record<StatementLocale, Required<StatementLocalizedFields>>;
}
