/**
 * Products and the product catalog lists (API reference: "Products", "Product catalog").
 *
 * - Catalog lists (categories, certifications, attributes, detail labels) are set up
 *   once and referenced by id from products. Items used by a product can't be deleted
 *   (409 names the products).
 * - A product is created and saved whole in one request (shared data, every variant and
 *   the text of any languages). Text is published per language; shared changes (prices,
 *   variants, images) go live with the next publish of any language.
 */
import { api, apiPaged } from "./api";
import type { Img, Status } from "./cms";

/* ------------------------------------------------------------------ */
/* Catalog lists                                                       */
/* ------------------------------------------------------------------ */

type Stamps = { createdAt: string; updatedAt: string };
/** `translations` keyed by language code; English is always present. */
export type Translations<T> = Record<string, T>;

export type Category = Stamps & {
  id: string;
  slug: string;
  /** The group's id; null for a group. */
  parentId: string | null;
  isGroup: boolean;
  order: number;
  image: Img | null;
  isActive: boolean;
  translations: Translations<{ name: string; description: string | null }>;
  /** Groups only: their categories, in order. */
  children?: Category[];
};
export type Certification = Stamps & { id: string; slug: string; order: number; logo: Img | null; isActive: boolean; translations: Translations<{ name: string; description: string | null }> };
export type AttributeValue = { id: string; slug: string; order: number; translations: Translations<{ label: string }> };
export type Attribute = Stamps & { id: string; slug: string; order: number; translations: Translations<{ name: string; description: string | null }>; values: AttributeValue[] };
export type DetailLabel = Stamps & { id: string; slug: string; order: number; translations: Translations<{ label: string }> };

/** Body of a catalog item create/update. Translations sent replace those languages; null removes one (not English). */
export type CatalogBody = Record<string, unknown>;

/** list / create / get / update / reorder / delete of one catalog list. */
function catalogList<T>(path: string) {
  return {
    list: () => api<T[]>(path),
    create: (body: CatalogBody) => api<T>(path, { method: "POST", body }),
    update: (id: string, body: CatalogBody) => api<T>(`${path}/${id}`, { method: "PATCH", body }),
    /** Every id of that list once, in display order (for categories: the groups, or the categories of one group). */
    reorder: (ids: string[]) => api<T[]>(`${path}/order`, { method: "PUT", body: { ids } }),
    remove: (id: string) => api<void>(`${path}/${id}`, { method: "DELETE" }),
  };
}

export const categoriesApi = catalogList<Category>("/admin/product-categories");
export const certificationsApi = catalogList<Certification>("/admin/certifications");
export const detailLabelsApi = catalogList<DetailLabel>("/admin/detail-labels");
export const attributesApi = {
  ...catalogList<Attribute>("/admin/attributes"),
  addValue: (id: string, body: { slug: string; translations: Translations<{ label: string }>; order?: number }) => api<Attribute>(`/admin/attributes/${id}/values`, { method: "POST", body }),
  updateValue: (id: string, valueId: string, body: { translations?: Translations<{ label: string } | null>; order?: number }) =>
    api<Attribute>(`/admin/attributes/${id}/values/${valueId}`, { method: "PATCH", body }),
  reorderValues: (id: string, ids: string[]) => api<Attribute>(`/admin/attributes/${id}/values/order`, { method: "PUT", body: { ids } }),
  removeValue: (id: string, valueId: string) => api<Attribute>(`/admin/attributes/${id}/values/${valueId}`, { method: "DELETE" }),
};

/** Name of a catalog item in a language, falling back to English. */
export function tr<T extends Record<string, unknown>>(t: Translations<T> | undefined, lang: string, field: keyof T): string {
  const v = t?.[lang]?.[field] ?? t?.en?.[field];
  return typeof v === "string" ? v : "";
}

/** Lowercase letters/numbers joined by single hyphens, from any text (slug suggestion). */
export const slugify = (s: string) =>
  s
    .normalize("NFKD")
    .replace(/[̀-ͯ]/g, "")
    .toLowerCase()
    .replace(/&/g, " and ")
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "")
    .slice(0, 80)
    .replace(/-+$/g, "");

export const isSlug = (s: string) => /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(s);

/* ------------------------------------------------------------------ */
/* Products                                                            */
/* ------------------------------------------------------------------ */

export const CURRENCIES = ["EUR", "USD", "GBP", "CHF", "AED", "SAR", "CNY", "INR", "JPY"] as const;
export const PRICE_UNITS = ["kg", "mt", "pack", "unit"] as const;
export const MOQ_UNITS = ["kg", "mt", "unit"] as const;
export const LENGTH_UNITS = ["mm", "cm", "m"] as const;
export const WEIGHT_UNITS = ["g", "kg"] as const;

export type ProductFile = { url: string; label: string };
export type Variant = {
  id?: string;
  sku: string;
  /** { attributeId: valueSlug }, every product attribute once; {} for a simple product. */
  attributeValues: Record<string, string>;
  /** Cents. */
  marketPrice?: number | null;
  /** Cents; at most marketPrice. */
  sellingPrice: number;
  dimensions?: { length: number; width: number; height: number; unit: (typeof LENGTH_UNITS)[number] } | null;
  weight?: { value: number; unit: (typeof WEIGHT_UNITS)[number] } | null;
  image?: Img | null;
  gallery?: Img[];
  isDefault?: boolean;
  isActive?: boolean;
};
export type ProductText = {
  name: string;
  shortDescription?: string | null;
  description?: string | null;
  /** { detailLabelId: text } */
  details?: Record<string, string>;
  seo?: { title?: string | null; description?: string | null };
};

/** The shared part of a product (draft / published). */
export type ProductData = {
  type: "simple" | "variable";
  categoryIds: string[];
  certificationIds: string[];
  originCountries: string[];
  farming: "organic" | "conventional";
  volumeMt: { min: number; max?: number | null };
  moq?: { value: number; unit: (typeof MOQ_UNITS)[number] } | null;
  currency: (typeof CURRENCIES)[number];
  priceUnit: (typeof PRICE_UNITS)[number];
  priceVisibility: "show" | "on-request";
  featured: boolean;
  order: number;
  thumbnail: Img;
  gallery: Img[];
  files: ProductFile[];
  attributes: { attributeId: string; values: string[] }[];
  variants: Variant[];
};

type Who = { id: string; email: string } | null;
export type ProductTranslation = {
  status: Status;
  source: "manual" | "ai" | null;
  draft: ProductText | null;
  published: ProductText | null;
  hasUnpublishedChanges: boolean;
  reviewComment: string | null;
  updatedBy: Who;
  updatedAt: string | null;
  submittedAt: string | null;
  publishedBy: Who;
  publishedAt: string | null;
};

/** GET /admin/products/:id */
export type Product = {
  id: string;
  slug: string;
  previousSlugs: string[];
  status: "active" | "archived";
  /** Send back on save; a stale one answers 409. */
  version: number;
  type: "simple" | "variable";
  draft: ProductData;
  published: ProductData | null;
  hasUnpublishedSharedChanges: boolean;
  translations: Record<string, ProductTranslation>;
  /** On the website now. */
  isLive: boolean;
  firstPublishedAt: string | null;
  createdAt: string;
  updatedAt: string;
};

/** Create / save body: the whole product. */
export type ProductBody = Omit<ProductData, "featured" | "order"> & {
  slug: string;
  featured?: boolean;
  order?: number;
  translations?: Record<string, ProductText>;
  source?: "ai";
  version?: number;
  confirmRemovals?: boolean;
};

/** A row of GET /admin/products. */
export type ProductRow = {
  id: string;
  slug: string;
  type: "simple" | "variable";
  status: "active" | "archived";
  name: string;
  thumbnail: Img | null;
  defaultSku: string | null;
  variantCount: number;
  price: { currency: string; unit: string; min: number | null; max: number | null } | null;
  /** Text state per language that has text. */
  languages: Record<string, Exclude<Status, null>>;
  version: number;
  updatedAt: string;
};

export type ProductQuery = {
  page: number;
  limit: number;
  search: string;
  category: string;
  type: "" | "simple" | "variable";
  status: "" | "active" | "archived";
  lang: string;
  state: "" | "draft" | "in_review" | "published" | "missing";
  sort: string;
};

export const productsApi = {
  list: (q: ProductQuery) =>
    apiPaged<ProductRow>("/admin/products", {
      page: q.page,
      limit: q.limit,
      sort: q.sort,
      search: q.search.trim() || undefined,
      category: q.category || undefined,
      type: q.type || undefined,
      status: q.status || undefined,
      // `lang` filters only together with `state`.
      lang: q.state ? q.lang || "en" : undefined,
      state: q.state || undefined,
    }),
  get: (id: string) => api<Product>(`/admin/products/${id}`),
  create: (body: ProductBody) => api<Product>("/admin/products", { method: "POST", body }),
  save: (id: string, body: ProductBody) => api<Product>(`/admin/products/${id}`, { method: "PUT", body }),
  skuCheck: (sku: string, productId?: string) => api<{ sku: string; available: boolean; usedBy: string | null }>("/admin/products/sku-check", { query: { sku, productId } }),
  action: (id: string, action: "submit" | "publish" | "unpublish", lang: string) => api<Product>(`/admin/products/${id}/${action}`, { method: "POST", query: { lang } }),
  reject: (id: string, lang: string, comment: string) => api<Product>(`/admin/products/${id}/reject`, { method: "POST", query: { lang }, body: { comment } }),
  /** The product page as the website would show it, with drafts. */
  preview: (id: string, lang: string) => api<unknown>(`/admin/products/${id}/preview`, { query: { lang } }),
  setStatus: (id: string, status: "active" | "archived") => api<Product>(`/admin/products/${id}/status`, { method: "PATCH", body: { status } }),
  duplicate: (id: string, slug: string) => api<Product>(`/admin/products/${id}/duplicate`, { method: "POST", body: { slug } }),
  remove: (id: string) => api<void>(`/admin/products/${id}`, { method: "DELETE" }),
};

/* ------------------------------------------------------------------ */
/* Display                                                             */
/* ------------------------------------------------------------------ */

/** Cents → "€480.00" (the API stores prices as integers in cents). */
export function money(cents: number | null | undefined, currency: string, locale = "en"): string {
  if (cents == null) return "";
  try {
    return new Intl.NumberFormat(locale, { style: "currency", currency }).format(cents / 100);
  } catch {
    return `${(cents / 100).toFixed(2)} ${currency}`;
  }
}

/** Badge for a language of a product (list column, language tabs). */
export function langBadge(state: Status | "missing" | undefined, hasUnpublishedChanges = false): { label: string; tone: "g" | "a" | "b" | "n" | "r" } {
  if (state === "published") return hasUnpublishedChanges ? { label: "Changes not published", tone: "a" } : { label: "Published", tone: "g" };
  if (state === "in_review") return { label: "In review", tone: "a" };
  if (state === "draft") return { label: "Draft", tone: "b" };
  return { label: "Missing", tone: "n" };
}
