import { fetchGraphQL } from "../client";
import { SEO_FIELDS } from "../fragments";
import type { WpLieu } from "../types";

const IMAGE_FIELDS = /* GraphQL */ `
  {
    node {
      sourceUrl
      altText
      mediaDetails {
        width
        height
      }
    }
  }
`;

const FICHE_LIEU_FIELDS = /* GraphQL */ `
  {
    pageType
    pays
    ville
    departement
    departementNom
    departementNum
    region
    typeZone
    slugVille
    slugDepartement
    slugRegion
    isDepartementPage
    heroImage ${IMAGE_FIELDS}
    heroImageCredit
    heroImageSource
    villesDepartement {
      nom
      slug
      typeZone
    }
    villesProches {
      nom
    }
    maillage {
      nom
      slug
      typeZone
    }
    maillageScope
    climatDescription
    zoneClimatique
    zoneClimatiqueCee
    descriptionClimatique
    joursSup30c
    tempMoyEstivale
    picHistorique
    joursSup30c10ans
    tempMoyEstivale10ans
    joursSup30c20ans
    tempMoyEstivale20ans
    reductionSousToiture
    introSection {
      hook
      accroche
      kpis {
        value
        label
      }
      contexte
      coutCache
      trustLine
      urgenceLine
    }
    content {
      activitesIntro
      secteurs {
        label
        image ${IMAGE_FIELDS}
        stat
        description
      }
      problemeTitlePart1
      problemeTitlePart2
      problemeParagraph
      solutionTitlePart1
      solutionTitlePart2
      solutionParagraph
      preuveBigStat1
      preuveBigStat2
      preuveParagraph
    }
    seoContent {
      h2
      intro
      sections {
        h3
        content
      }
    }
  }
`;

const LIEU_QUERY = /* GraphQL */ `
  query GetLieu($slug: ID!) {
    lieu(id: $slug, idType: SLUG) {
      id
      slug
      title
      seo ${SEO_FIELDS}
      ficheLieu ${FICHE_LIEU_FIELDS}
    }
  }
`;

/** Récupère une page lieu (CPT `lieu`) par slug racine. */
export async function getLieu(slug: string): Promise<WpLieu | null> {
  const data = await fetchGraphQL<{ lieu: WpLieu | null }>(
    LIEU_QUERY,
    { slug },
    { tags: ["lieu", `lieu:${slug}`] }
  );
  return data.lieu ?? null;
}

const ALL_LIEU_SLUGS_QUERY = /* GraphQL */ `
  query GetAllLieuSlugs($after: String) {
    lieux(first: 100, after: $after, where: { status: PUBLISH }) {
      pageInfo {
        hasNextPage
        endCursor
      }
      nodes {
        slug
      }
    }
  }
`;

/** Liste tous les slugs de lieux publiés (pagination par curseur). */
export async function getAllLieuSlugs(): Promise<string[]> {
  const slugs: string[] = [];
  let after: string | null = null;
  let hasNextPage = true;

  while (hasNextPage) {
    const data = await fetchGraphQL<{
      lieux: {
        pageInfo: { hasNextPage: boolean; endCursor: string | null };
        nodes: { slug: string | null }[] | null;
      } | null;
    }>(ALL_LIEU_SLUGS_QUERY, { after }, { tags: ["lieu"] });

    const lieux = data.lieux;
    for (const node of lieux?.nodes ?? []) {
      if (node.slug) slugs.push(node.slug);
    }
    hasNextPage = Boolean(lieux?.pageInfo?.hasNextPage);
    after = lieux?.pageInfo?.endCursor ?? null;
  }

  return slugs;
}
