/**
 * "Import website products": creates in the CMS, as drafts, what the website's designed
 * catalogue shows today (app/(site)/_components/pages/global-agriculture/builtInProducts.ts):
 * the category groups and categories, certifications and the "Used in" detail label
 * (reused when an item with the same slug exists), then each product not created yet.
 * Nothing goes live until it is published.
 */
import { ApiError, errorMessage } from "./api";
import { categoriesApi, certificationsApi, detailLabelsApi, productsApi, type Category, type ProductBody } from "./products";
import {
  BUILT_IN_CATEGORIES,
  BUILT_IN_CERTIFICATIONS,
  BUILT_IN_DETAIL_LABEL,
  BUILT_IN_PRODUCTS,
  PRODUCT_TEMPLATE,
} from "@/app/(site)/_components/pages/global-agriculture/builtInProducts";

export { BUILT_IN_PRODUCTS };

export type ImportResult = { created: string[]; skipped: string[]; catalog: string[]; failed: string[] };

const en = (name: string) => ({ en: { name } });

/** Ids of the built-in catalog items by slug, creating the missing ones. `created` gets their names. */
async function ensureCatalog(created: string[]) {
  const groups = await categoriesApi.list();
  const all: Category[] = groups.flatMap((g) => [g, ...(g.children ?? [])]);
  const categoryIds: Record<string, string> = {};
  for (const g of BUILT_IN_CATEGORIES) {
    let group = groups.find((x) => x.slug === g.slug);
    if (!group) {
      group = await categoriesApi.create({ slug: g.slug, translations: en(g.name) });
      created.push(g.name);
    }
    for (const c of g.categories) {
      let cat = all.find((x) => x.slug === c.slug);
      if (!cat) {
        cat = await categoriesApi.create({ slug: c.slug, parentId: group.id, translations: en(c.name) });
        created.push(c.name);
      }
      categoryIds[c.slug] = cat.id;
    }
  }

  const certs = await certificationsApi.list();
  const certificationIds: Record<string, string> = {};
  for (const c of BUILT_IN_CERTIFICATIONS) {
    let cert = certs.find((x) => x.slug === c.slug);
    if (!cert) {
      cert = await certificationsApi.create({ slug: c.slug, translations: en(c.name) });
      created.push(c.name);
    }
    certificationIds[c.slug] = cert.id;
  }

  const labels = await detailLabelsApi.list();
  let label = labels.find((x) => x.slug === BUILT_IN_DETAIL_LABEL.slug);
  if (!label) {
    label = await detailLabelsApi.create({ slug: BUILT_IN_DETAIL_LABEL.slug, translations: { en: { label: BUILT_IN_DETAIL_LABEL.label } } });
    created.push(`"${BUILT_IN_DETAIL_LABEL.label}" label`);
  }
  return { categoryIds, certificationIds, usedInId: label.id };
}

/**
 * Runs the import. `existing` = slugs already in the CMS (skipped). `onProgress` gets a
 * short status line while it works.
 */
export async function importWebsiteProducts(existing: Set<string>, onProgress: (msg: string) => void): Promise<ImportResult> {
  const result: ImportResult = { created: [], skipped: [], catalog: [], failed: [] };
  onProgress("Setting up the catalog lists…");
  const ids = await ensureCatalog(result.catalog);

  for (const [i, p] of BUILT_IN_PRODUCTS.entries()) {
    if (existing.has(p.slug)) {
      result.skipped.push(p.name);
      continue;
    }
    onProgress(`Creating ${p.name} (${i + 1} of ${BUILT_IN_PRODUCTS.length})…`);
    const body = (sellingPrice: number): ProductBody => ({
      type: "simple",
      slug: p.slug,
      categoryIds: [ids.categoryIds[p.category]],
      certificationIds: [ids.certificationIds[PRODUCT_TEMPLATE.certification]],
      originCountries: PRODUCT_TEMPLATE.originCountries,
      farming: "conventional",
      volumeMt: { min: 0 },
      currency: "EUR",
      priceUnit: "kg",
      // The design shows no prices: on request until real prices are entered.
      priceVisibility: "on-request",
      featured: false,
      order: i,
      thumbnail: p.thumbnail,
      gallery: [],
      files: [],
      attributes: [],
      variants: [{ sku: `${p.slug.toUpperCase()}-01`, attributeValues: {}, sellingPrice, isDefault: true, isActive: true }],
      translations: {
        en: {
          name: p.name,
          shortDescription: PRODUCT_TEMPLATE.shortDescription,
          description: PRODUCT_TEMPLATE.description,
          details: { [ids.usedInId]: BUILT_IN_DETAIL_LABEL.text },
        },
      },
    });
    try {
      try {
        await productsApi.create(body(0));
      } catch (e) {
        // The reference doesn't say whether a price of 0 is accepted; a 1-cent placeholder is hidden while the price is on request.
        if (e instanceof ApiError && e.status === 400 && e.errors.some((m) => m.includes("sellingPrice"))) await productsApi.create(body(1));
        else throw e;
      }
      result.created.push(p.name);
    } catch (e) {
      if (e instanceof ApiError && e.status === 409) result.skipped.push(p.name);
      else result.failed.push(`${p.name}: ${errorMessage(e)}`);
    }
  }
  return result;
}

/**
 * "Add priced sample product": one product with its price shown, to see a priced card on
 * Global Agriculture. Featured, so the catalogue's default sort lists it first.
 */
export const PRICED_SAMPLE = {
  slug: "garam-masala-spice-blend",
  sku: "GARAM-MASALA-01",
  name: "Garam Masala Spice Blend",
  category: "spices-herbs",
  /** Cents per kg. */
  sellingPrice: 1250,
  marketPrice: 1490,
  thumbnail: { url: "/assets/images/global-agriculture/intro-spices.jpg", alt: "Bowls of ground spices with cinnamon sticks, star anise and fennel seeds" },
  shortDescription: "A warm, aromatic blend of cinnamon, fennel, star anise and black pepper, milled for food manufacturers.",
  description: [
    "Our Garam Masala blend combines whole spices sourced from certified growers, roasted and milled in small batches to keep their aromatic oils.",
    "It is supplied in food-grade bulk packaging for ready meals, sauces, snacks and seasoning mixes, with full lot traceability from farm to shipment.",
  ].join("\n\n"),
  usedIn: "Ready meals, sauces & seasoning blends",
};

export type PricedSampleResult = { id: string; published: boolean; publishError: string | null };

/** Creates the priced sample product and publishes its English text (left as a draft if publishing is refused). */
export async function addPricedSample(onProgress: (msg: string) => void): Promise<PricedSampleResult> {
  onProgress("Setting up the catalog lists…");
  const ids = await ensureCatalog([]);
  const p = PRICED_SAMPLE;
  onProgress(`Creating ${p.name}…`);
  const product = await productsApi.create({
    type: "simple",
    slug: p.slug,
    categoryIds: [ids.categoryIds[p.category]],
    certificationIds: [ids.certificationIds.halal, ids.certificationIds[PRODUCT_TEMPLATE.certification]],
    originCountries: ["IN"],
    farming: "conventional",
    volumeMt: { min: 1, max: 200 },
    currency: "EUR",
    priceUnit: "kg",
    priceVisibility: "show",
    featured: true,
    order: 0,
    thumbnail: p.thumbnail,
    gallery: [],
    files: [],
    attributes: [],
    variants: [{ sku: p.sku, attributeValues: {}, marketPrice: p.marketPrice, sellingPrice: p.sellingPrice, isDefault: true, isActive: true }],
    translations: { en: { name: p.name, shortDescription: p.shortDescription, description: p.description, details: { [ids.usedInId]: p.usedIn } } },
  });
  onProgress(`Publishing ${p.name}…`);
  try {
    await productsApi.action(product.id, "publish", "en");
    return { id: product.id, published: true, publishError: null };
  } catch (e) {
    return { id: product.id, published: false, publishError: errorMessage(e) };
  }
}
