/**
 * Articles and their categories (API reference: "Articles", "Article categories",
 * "How articles work (admin panel)").
 *
 * - An article is saved whole: the shared fields (category, cover image, author, slug)
 *   and the text of the languages sent. Shared fields change on the website at once;
 *   text changes wait until that language is published.
 * - Text is published per language (submit, publish, reject, unpublish). Archive takes
 *   the article off the website in every language; only never-published articles can
 *   be deleted.
 * - Categories are the Thought Leadership page's filter tabs.
 */
import { ApiError, api, apiPaged } from "./api";
import type { Img } from "./cms";
import type { Media } from "./media";

type Who = { id: string; email: string } | null;
export type Translations<T> = Record<string, T>;

export type ArticleCategory = {
  id: string;
  slug: string;
  order: number;
  isActive: boolean;
  translations: Translations<{ name: string; description: string | null }>;
  createdAt: string;
  updatedAt: string;
};

export type ArticleBlock =
  | { type: "paragraph"; text: string }
  | { type: "heading"; level: 2 | 3; text: string }
  | { type: "list"; style: "bullet" | "numbered"; items: string[] }
  | { type: "quote"; text: string; source?: string | null }
  | { type: "image"; url: string; alt?: string | null; caption?: string | null };
export type BlockType = ArticleBlock["type"];

export type ArticleText = { title: string; excerpt: string; body: ArticleBlock[]; seo?: { title?: string | null; description?: string | null } | null };

export type TextStatus = "draft" | "in_review" | "published";

export type ArticleTranslation = {
  status: TextStatus;
  source: "manual" | "ai" | null;
  /** The text being edited (null when only the published text exists). */
  draft: ArticleText | null;
  /** The live text. */
  published: ArticleText | null;
  reviewComment: string | null;
  updatedBy: Who;
  updatedAt: string | null;
  submittedBy: Who;
  submittedAt: string | null;
  reviewedBy: Who;
  reviewedAt: string | null;
  publishedBy: Who;
  publishedAt: string | null;
  readingMinutes: number;
};

export type Author = { name: string; role?: string | null };

/** GET /admin/articles/:id */
export type Article = {
  id: string;
  slug: string;
  previousSlugs: string[];
  path: string;
  status: "active" | "archived";
  categoryId: string;
  category: { slug: string; name: string } | null;
  coverImage: Img;
  author: Author | null;
  translations: Record<string, ArticleTranslation>;
  liveLanguages: string[];
  /** Active and live in at least one language. */
  live: boolean;
  firstPublishedAt: string | null;
  /** Send back on save; a stale one answers 409. */
  version: number;
  createdAt: string;
  updatedAt: string;
};

/** Create / save body. A language sent becomes that language's draft; null removes it (not English). */
export type ArticleSaveBody = {
  translations: Record<string, ArticleText | null>;
  categoryId: string;
  coverImage: Img;
  author?: Author | null;
  slug?: string;
  version?: number;
};

/** A row of GET /admin/articles. */
export type ArticleRow = {
  id: string;
  slug: string;
  status: "active" | "archived";
  title: string;
  category: { slug: string; name: string } | null;
  coverImage: Img | null;
  languages: Record<string, { status: TextStatus; live: boolean }>;
  live: boolean;
  firstPublishedAt: string | null;
  createdAt: string;
  updatedAt: string;
};

export type ArticleQuery = {
  page: number;
  limit: number;
  search: string;
  category: string;
  status: "" | "active" | "archived";
  lang: string;
  state: "" | TextStatus | "missing";
  sort: string;
};

export const articlesApi = {
  list: (q: ArticleQuery) =>
    apiPaged<ArticleRow>("/admin/articles", {
      page: q.page,
      limit: q.limit,
      sort: q.sort,
      search: q.search.trim() || undefined,
      category: q.category || undefined,
      status: q.status || undefined,
      lang: q.lang || undefined,
      state: q.state || undefined,
    }),
  get: (id: string) => api<Article>(`/admin/articles/${id}`),
  create: (body: ArticleSaveBody) => api<Article>("/admin/articles", { method: "POST", body }),
  save: (id: string, body: ArticleSaveBody) => api<Article>(`/admin/articles/${id}`, { method: "PUT", body }),
  /** The article page as the website would show it, with drafts (falls back to English). */
  preview: (id: string, lang: string) => api<unknown>(`/admin/articles/${id}/preview`, { query: { lang } }),
  action: (id: string, action: "submit" | "publish" | "unpublish", lang: string) => api<Article>(`/admin/articles/${id}/${action}`, { method: "POST", query: { lang } }),
  reject: (id: string, lang: string, comment: string) => api<Article>(`/admin/articles/${id}/reject`, { method: "POST", query: { lang }, body: { comment } }),
  setStatus: (id: string, status: "active" | "archived") => api<Article>(`/admin/articles/${id}/status`, { method: "PATCH", body: { status } }),
  remove: (id: string) => api<void>(`/admin/articles/${id}`, { method: "DELETE" }),
};

/* ------------------------------------------------------------------ */
/* Body images: the address form the API accepts                        */
/* ------------------------------------------------------------------ */

/*
 * Media library files have three addresses: the public one the admin saves elsewhere
 * (media host + /uploads/…), the one the API returns on upload (its own host, e.g.
 * http://localhost:4012/uploads/…) and the bare path (/uploads/…). The cover image is
 * accepted in the public form, but the live API refused a body image in that form
 * ("must be an image uploaded to the media library"), and the reference doesn't say
 * which form it matches. So a refused body image is retried in the other two forms, and
 * the form that works is used from then on. The website shows all three (mediaSrc).
 */
type ImageForm = "public" | "api" | "path";
let acceptedForm: ImageForm = "public";
let apiOrigin: string | null | undefined;

/** The API's own host for uploads (from any media item: url minus path), or null when unknown. */
async function getApiOrigin(): Promise<string | null> {
  if (apiOrigin !== undefined) return apiOrigin;
  try {
    const m = (await apiPaged<Media>("/admin/media", { limit: 1, page: 1 })).data[0];
    apiOrigin = m?.url && m.path && m.url.endsWith(m.path) ? m.url.slice(0, -m.path.length) : null;
  } catch {
    apiOrigin = null;
  }
  return apiOrigin;
}

async function inForm(url: string, form: ImageForm, publicOrigin: string): Promise<string> {
  const path = /^(?:https?:\/\/[^/]+)?(\/uploads\/.+)$/i.exec(url.trim())?.[1];
  if (!path) return url; // not a library file (e.g. a website picture): leave it
  if (form === "path") return path;
  if (form === "api") {
    const origin = await getApiOrigin();
    return origin ? origin + path : url;
  }
  return publicOrigin + path;
}

/** The body with every image block's address in `form`. */
async function withImageForm(body: ArticleSaveBody, form: ImageForm, publicOrigin: string): Promise<ArticleSaveBody> {
  const translations: ArticleSaveBody["translations"] = {};
  for (const [l, t] of Object.entries(body.translations)) {
    translations[l] = t && { ...t, body: await Promise.all(t.body.map(async (b) => (b.type === "image" ? { ...b, url: await inForm(b.url, form, publicOrigin) } : b))) };
  }
  return { ...body, translations };
}

const refusedBodyImage = (e: unknown) => e instanceof ApiError && e.status === 400 && e.errors.some((m) => /\.body\.\d+\.url\b.*media library/i.test(m));

/**
 * Create or save an article (`send`), retrying refused body images in the other address
 * forms. `publicOrigin` is the media host the admin uses (MEDIA_ORIGIN).
 */
export async function sendArticle(send: (b: ArticleSaveBody) => Promise<Article>, body: ArticleSaveBody, publicOrigin: string): Promise<Article> {
  const first = acceptedForm;
  try {
    return await send(first === "public" ? body : await withImageForm(body, first, publicOrigin));
  } catch (e) {
    if (!refusedBodyImage(e)) throw e;
    for (const form of (["public", "api", "path"] as const).filter((f) => f !== first)) {
      try {
        const a = await send(await withImageForm(body, form, publicOrigin));
        acceptedForm = form;
        return a;
      } catch (e2) {
        if (!refusedBodyImage(e2)) throw e2;
      }
    }
    throw e;
  }
}

const CATEGORIES = "/admin/article-categories";
export const articleCategoriesApi = {
  list: () => api<ArticleCategory[]>(CATEGORIES),
  create: (body: Record<string, unknown>) => api<ArticleCategory>(CATEGORIES, { method: "POST", body }),
  update: (id: string, body: Record<string, unknown>) => api<ArticleCategory>(`${CATEGORIES}/${id}`, { method: "PATCH", body }),
  /** Every category id once, in display order. */
  reorder: (ids: string[]) => api<ArticleCategory[]>(`${CATEGORIES}/order`, { method: "PUT", body: { ids } }),
  remove: (id: string) => api<void>(`${CATEGORIES}/${id}`, { method: "DELETE" }),
};

/**
 * Badge for a language of an article. Saving a published language makes it a draft
 * again while the published text stays live: that is "Changes not published".
 */
export function articleLangBadge(status: TextStatus | "missing" | undefined, live: boolean): { label: string; tone: "g" | "a" | "b" | "n" } {
  if (status === "published") return { label: "Published", tone: "g" };
  if (status === "in_review") return { label: live ? "Changes in review" : "In review", tone: "a" };
  if (status === "draft") return live ? { label: "Changes not published", tone: "a" } : { label: "Draft", tone: "b" };
  return { label: "Missing", tone: "n" };
}

/** Block types offered in the editor, in menu order. */
export const BLOCK_TYPES: { type: BlockType; label: string }[] = [
  { type: "paragraph", label: "Paragraph" },
  { type: "heading", label: "Heading" },
  { type: "list", label: "List" },
  { type: "quote", label: "Quote" },
  { type: "image", label: "Image" },
];
