import { fetchGraphQL } from "../client";
import { 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 { WpIndustrie } from "../types";

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

const INDUSTRIE_QUERY = /* GraphQL */ `
  ${SECTIONS_FRAGMENTS}
  query GetIndustrie($slug: ID!) {
    industrie(id: $slug, idType: SLUG) {
      id
      slug
      title
      ${LANG_FIELDS}
      seo ${SEO_FIELDS}
      ${SECTIONS_FIELD}
      ${INDUSTRIE_TRANSLATIONS}
    }
  }
`;

/** Récupère une page secteur (CPT `industrie`, rewrite /industries) par slug + locale. */
export async function getIndustrie(slug: string, locale: Locale = "fr"): Promise<WpIndustrie | null> {
  const data = await fetchGraphQL<{ industrie: WpIndustrie | null }>(
    INDUSTRIE_QUERY,
    { slug },
    { tags: ["industrie", locale === "fr" ? `industrie:${slug}` : `industrie:${locale}:${slug}`] }
  );
  return pickLang(data.industrie ?? null, locale);
}

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

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

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

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

  return slugs;
}
