import { fetchGraphQL } from "../client";
import { FILE_FIELDS, SECTIONS_FIELD, SECTIONS_FRAGMENTS, SEO_FIELDS } from "../fragments";
import { type Locale } from "@/config/i18nRoutes";
import { WP_I18N_ENABLED } from "../flags";
import { pickLang } from "../i18n";
import type { WpProduit } from "../types";

const FICHE_PRODUIT_FIELDS = /* GraphQL */ `
  ficheProduit {
    productName
    tagline
    accentColor
    garantie
    sri
    prix
    ficheTechniquePdf ${FILE_FIELDS}
  }
`;

const LANG_FIELDS = WP_I18N_ENABLED ? `language { code slug }` : ``;
const PRODUIT_TRANSLATIONS = WP_I18N_ENABLED
  ? `translations { id slug title language { code slug } seo ${SEO_FIELDS} ${FICHE_PRODUIT_FIELDS} ${SECTIONS_FIELD} }`
  : ``;

const PRODUIT_QUERY = /* GraphQL */ `
  ${SECTIONS_FRAGMENTS}
  query GetProduit($slug: ID!) {
    produit(id: $slug, idType: SLUG) {
      id
      slug
      title
      ${LANG_FIELDS}
      seo ${SEO_FIELDS}
      ${FICHE_PRODUIT_FIELDS}
      ${SECTIONS_FIELD}
      ${PRODUIT_TRANSLATIONS}
    }
  }
`;

/** Récupère un produit (CPT `produit`, rewrite /solutions) par slug + locale. */
export async function getProduit(slug: string, locale: Locale = "fr"): Promise<WpProduit | null> {
  const data = await fetchGraphQL<{ produit: WpProduit | null }>(
    PRODUIT_QUERY,
    { slug },
    { tags: ["produit", locale === "fr" ? `produit:${slug}` : `produit:${locale}:${slug}`] }
  );
  return pickLang(data.produit ?? null, locale);
}

const ALL_PRODUIT_SLUGS_QUERY = /* GraphQL */ `
  query GetAllProduitSlugs($after: String) {
    produits(first: 100, after: $after, where: { status: PUBLISH }) {
      pageInfo {
        hasNextPage
        endCursor
      }
      nodes {
        slug
        ${WP_I18N_ENABLED ? "language { slug }" : ""}
      }
    }
  }
`;

/** Liste les slugs de produits publiés dans une langue (filtrage langue côté JS). */
export async function getAllProduitSlugs(locale: Locale = "fr"): Promise<string[]> {
  const slugs: string[] = [];
  let after: string | null = null;
  let hasNextPage = true;

  while (hasNextPage) {
    const data = await fetchGraphQL<{
      produits: {
        pageInfo: { hasNextPage: boolean; endCursor: string | null };
        nodes: { slug: string | null; language?: { slug?: string | null } | null }[] | null;
      } | null;
    }>(ALL_PRODUIT_SLUGS_QUERY, { after }, { tags: ["produit"] });

    const produits = data.produits;
    for (const node of produits?.nodes ?? []) {
      if (!node.slug) continue;
      if (WP_I18N_ENABLED && node.language?.slug && node.language.slug !== locale) continue;
      slugs.push(node.slug);
    }
    hasNextPage = Boolean(produits?.pageInfo?.hasNextPage);
    after = produits?.pageInfo?.endCursor ?? null;
  }

  return slugs;
}
