import type { TemporaryStatementState } from "@accessibit/types";
import type { StatementStatus } from "./statementForm";

/**
 * What the page says a statement is, in one word, on top of the page.
 *
 * Not the row's `status`: every save puts that back to `draft`, published
 * pages included, so an incomplete save of a statement that is online would
 * read "draft" over a page visitors can open. What is online decides, and the
 * row's status only says whether a generation is running or failed.
 */
export type StatementState =
  | "generating"
  | "failed"
  | "temporary"
  | "published"
  | "nothingOnline"
  | "draft";

export function statementState(input: {
  status: StatementStatus;
  /** The page is between its save and the queue answering: generating too. */
  busy: boolean;
  /** At least one language has a page online. */
  hasPublished: boolean;
  /** The site's temporary statement, when it has one. */
  temporary: TemporaryStatementState | null;
  /** The plan's end took the regular statement off the site (ACC-516). */
  withdrawn?: boolean;
}): StatementState {
  if (
    input.busy ||
    input.status === "queued" ||
    input.status === "processing"
  ) {
    return "generating";
  }
  if (input.status === "failed") return "failed";
  // While it is active the link shows it, whatever else is published.
  if (input.temporary === "active") return "temporary";
  // Published once, and taken back with the plan: the link shows nothing.
  if (input.withdrawn) return "nothingOnline";
  if (input.hasPublished) return "published";
  // It expired and there is no regular one to go back to: the link shows
  // nothing, which is worth more than "draft".
  if (input.temporary === "expired") return "nothingOnline";
  return "draft";
}
