/**
 * SAFL page data layer.
 *
 * Same pattern as homepage & green-energy: bundled defaults with
 * Strapi merge-over-defaults when enabled.
 */

import { fetchSingle, getMediaUrl } from "@/lib/strapi/client"
import { isStrapiEnabled } from "@/lib/strapi/config"
import { titleCase } from "@/lib/api/casing"
import { normalizeCmsLink } from "@/lib/api/links"
import type {
  SaflData,
  SaflStatCardData,
  SaflProductCategoryData,
  SaflProcessStepData,
  StrapiMedia,
} from "@/lib/strapi/types"

/* ------------------------------------------------------------------ */
/*  Bundled defaults                                                   */
/* ------------------------------------------------------------------ */

export const saflDefaults: SaflData = {
  hero: {
    heading: "Southern Agrifurane Industries Ltd.",
    description: "Crafting Premium Indian Made Foreign Spirits with Excellence Since 2001",
    mobileBackgroundImage: "/assets/safl/safl-hero-mobile.png",
    desktopBackgroundImage: "/assets/safl/safl-hero.png",
  },
  about: {
    badge: "about SAFL",
    badgeIcon: "/assets/safl/badge-star.svg",
    watermarkText: "About SAFL",
    decorativeImage: "/assets/safl/about-decorative.svg",
    paragraphs: [
      "Southern Agrifurane Industries Ltd. (SAFL), acquired on 21st September 2001, brings over two decades of experience and expertise in the Indian liquor industry. The company operates its own manufacturing facilities in Tamil Nadu and Telangana, with a combined production capacity of over 6.13 lakh cases per month in Tamil Nadu and 1.2 lakh cases per month in Telangana.",
      "In Tamil Nadu, SAFL operates an IMFL bottling unit at Ellichatram Road, Valudhareddy Village, and a distillery unit in Mundiyampakkam, both located in the Villupuram district. In Telangana, its operations include an IMFL bottling unit in Nandigama Village, Kothur Mandal, Ranga Reddy District.",
      "In addition to its owned facilities, SAFL strengthens its presence through strategic tie-up manufacturing in Kerala, Puducherry, and Andhra Pradesh, collectively contributing over 1 lakh cases per month. In Kerala, SAFL partners with The Devicolam Distilleries Ltd. and Normandy Breweries and Distilleries Pvt. Ltd., while in Puducherry, it collaborates with Vinbros & Co. In Andhra Pradesh (now Telangana), SAFL has expanded its capabilities through the acquisition of factories and brands from Kamal Wineries.",
      "These partnerships and acquisitions have enhanced SAFL's production capacity and geographic reach, enabling it to meet market demand efficiently. By combining owned operations with strategic collaborations, SAFL maintains consistent quality, ensures supply reliability, and strengthens its presence across South India's dynamic liquor industry.",
    ],
  },
  productRange: {
    badge: "Our RANGE.",
    badgeIcon: "/assets/safl/badge-star.svg",
    watermarkText: "Our Product Lineup",
    ctaLabel: "Location",
    ctaHref: "#product-range",
    categories: [
      {
        name: "Vodka",
        banners: [
          { name: "Gova Vodka", image: "/assets/vodka/Gova Vodka.jpg", mobileImage: "/assets/VodkaM/Gova Vodka.jpg" },
          { name: "Green Apple Vodka", image: "/assets/vodka/Green apple vodka.jpg", mobileImage: "/assets/VodkaM/GREEN APPLE VODKA.jpg" },
          { name: "Krystal Vodka", image: "/assets/vodka/Krystal vodka.jpg", mobileImage: "/assets/VodkaM/Kry Stal Vodka.jpg" },
          { name: "Lemon Vodka", image: "/assets/vodka/Lemon Vodka.jpg", mobileImage: "/assets/VodkaM/LIMON VODKA.jpg" },
          { name: "Orange Vodka", image: "/assets/vodka/Orange vodka.jpg", mobileImage: "/assets/VodkaM/ORANGE VODKA.jpg" },
        ],
      },
      {
        name: "Brandy",
        banners: [
          { name: "Celebrity Brandy", image: "/assets/Brandy/Celebrity Brandy.jpg", mobileImage: "/assets/brandyM/Celebrity Brandy.jpg" },
          { name: "Gold Reserve Brandy", image: "/assets/Brandy/Gold Reserve Brandy.jpg", mobileImage: "/assets/brandyM/Gold Reserve Brandy.jpg" },
          { name: "Gold VSOP", image: "/assets/Brandy/Gold Vsop.jpg", mobileImage: "/assets/brandyM/Gold VSOP Premium Brandy.jpg" },
          { name: "No 1 VSOP Brandy", image: "/assets/Brandy/No 1 Vsop Brandy.jpg", mobileImage: "/assets/brandyM/NO 1 VSOP BRANDY.jpg" },
          { name: "Richmans Grape Brandy", image: "/assets/Brandy/Richmans Grape Brandy.jpg", mobileImage: "/assets/brandyM/RICHMANS GRAPE BRANDY.jpg" },
        ],
      },
      {
        name: "Rum",
        banners: [
          { name: "Diamond Rum", image: "/assets/Rum/Diamond rum.jpg", mobileImage: "/assets/rumM/Diamond XXXRUM.jpg" },
          { name: "Richmans Rum", image: "/assets/Rum/Richmans rum.jpg", mobileImage: "/assets/rumM/RICHMANS XXX RUM.jpg" },
        ],
      },
      {
        name: "Whisky",
        banners: [
          { name: "Indian Challenge Whisky", image: "/assets/Whisky/Indian Challenge whisky.jpg", mobileImage: "/assets/wiskeyM/INDIAN CHALLENGE WHISKY.jpg" },
        ],
      },
    ],
  },
  stats: {
    badge: "Our Impact in Numbers",
    badgeIcon: "/assets/safl/badge-star.svg",
    description: "A reflection of our scale, reach, and steady growth built over years of purposeful progress",
    stats: [
      { number: "12.00", suffix: "Million Cases", description: "Total Production Capacity (Owned + Tie-ups)", vector: "/assets/safl/stats-vector-1.svg" },
      { number: "7.36", suffix: "Million Cases", description: "Operational Capacity Tamil Nadu (Licensed) per annum", vector: "/assets/safl/stats-vector-2.svg" },
      { number: "1.44", suffix: "Million Cases", description: "Operational Capacity Telangana (Licensed) per annum", vector: "/assets/safl/stats-vector-3.svg" },
      { number: "3.20", suffix: "Million Cases", description: "Operational Capacity Kerala (Tie-up Operations) per annum", vector: "/assets/safl/stats-vector-1.svg" },
    ],
  },
  process: {
    badge: "Our Liquor Crafting Process",
    badgeIcon: "/assets/safl/badge-star.svg",
    steps: [
      { title: "Spirit Preparation", description: "The process begins with the careful preparation and blending of spirits in a controlled environment. Purified water systems and selected ingredients are used to create balanced blends that ensure consistent taste, aroma, and quality. Each batch undergoes internal quality checks before moving to the next stage.", image: "/assets/safl/liquor-crafting-process.jpg" },
      { title: "Bottling", description: "Once approved, the spirit is transferred to the bottling facility, where automated and semi-automated lines ensure precise filling and secure sealing. These systems maintain high standards of hygiene, efficiency, and accuracy across various product formats and packaging styles.", image: "/assets/safl/liquor-crafting-process.jpg" },
      { title: "Quality Check & Labeling", description: "Every sealed bottle is thoroughly inspected for consistency, volume, and seal integrity. After passing the quality check, bottles are directed to the labeling units where they are precisely labeled and coded with manufacturing details.", image: "/assets/safl/liquor-crafting-process.jpg" },
      { title: "Packaging & Dispatch", description: "The labeled bottles are then securely packed into cartons and palletized. Our dispatch facility ensures that these finished products are safely loaded and transported through an optimized logistics network, delivering them to designated markets on time.", image: "/assets/safl/liquor-crafting-process.jpg" },
      { title: "Warehousing & Storage", description: "The packaged products are systematically organized and stored in our climate-controlled warehouses. Advanced inventory management systems ensure optimal stock rotation and preserve the quality of the spirits before they reach our partners.", image: "/assets/safl/liquor-crafting-process.jpg" },
      { title: "Distribution & Logistics", description: "Through a robust and highly coordinated logistics framework, the finalized products are transported efficiently. We adhere strictly to regulatory distribution standards to ensure smooth delivery to authorized retail and wholesale networks.", image: "/assets/safl/liquor-crafting-process.jpg" },
    ],
  },
}

/* ------------------------------------------------------------------ */
/*  Helpers                                                           */
/* ------------------------------------------------------------------ */

type AnyRec = Record<string, unknown>

function str(val: unknown, fallback = ""): string {
  if (typeof val === "string") return val.trim() !== "" ? val : fallback
  if (typeof val === "number") return String(val)
  return fallback
}

function media(val: unknown): string {
  return getMediaUrl(val as StrapiMedia | null | undefined)
}

function withFallback<T>(value: T[] | undefined | null, fallback: T[]): T[] {
  return value && value.length > 0 ? value : fallback
}

/* ------------------------------------------------------------------ */
/*  Public API                                                        */
/* ------------------------------------------------------------------ */

export async function getSaflData(): Promise<SaflData> {
  const d = saflDefaults

  if (!isStrapiEnabled) return d

  const entry = await fetchSingle<AnyRec>("safl")

  if (!entry) return d

  const hero = (entry.hero as AnyRec | undefined) ?? {}
  const about = (entry.about as AnyRec | undefined) ?? {}
  const productRange = (entry.productRange as AnyRec | undefined) ?? {}
  const statsWrapper = (entry.stats as AnyRec | undefined) ?? {}
  const processWrapper = (entry.process as AnyRec | undefined) ?? {}
  const categoryRows = (productRange.categories as AnyRec[] | undefined) ?? []
  const statRows = (statsWrapper.stats as AnyRec[] | undefined) ?? []
  const stepRows = (processWrapper.steps as AnyRec[] | undefined) ?? []
  const paragraphRows = (about.paragraphs as AnyRec[] | undefined) ?? []
  const processImage = media(processWrapper.image_3x2) || d.process.steps[0]?.image || ""

  return {
    hero: {
      heading: str(hero.heading, d.hero.heading),
      description: str(hero.description, d.hero.description),
      mobileBackgroundImage: media(hero.mobileBackgroundImage_9x16) || d.hero.mobileBackgroundImage,
      desktopBackgroundImage: media(hero.desktopBackgroundImage_2x1) || d.hero.desktopBackgroundImage,
    },
    about: {
      badge: str(about.badge, d.about.badge),
      badgeIcon: d.about.badgeIcon,
      watermarkText: titleCase(str(about.watermarkText, d.about.watermarkText)),
      decorativeImage: d.about.decorativeImage,
      paragraphs: withFallback(paragraphRows.map((row) => str(row.text)), d.about.paragraphs),
    },
    productRange: {
      badge: str(productRange.badge, d.productRange.badge),
      badgeIcon: d.productRange.badgeIcon,
      watermarkText: titleCase(str(productRange.watermarkText, d.productRange.watermarkText)),
      ctaLabel: str(productRange.ctaButtonText, d.productRange.ctaLabel),
      ctaHref: normalizeCmsLink(productRange.ctaButtonLink, d.productRange.ctaHref),
      categories: withFallback(categoryRows.map((cat) => {
        return {
          name: str(cat.name),
          banners: ((cat.banners as AnyRec[] | undefined) ?? []).map((banner) => {
            return {
              name: str(banner.name),
              image: media(banner.image_2x1) || str(banner.imageUrl),
              mobileImage: media(banner.mobileImage_4x5) || str(banner.mobileImageUrl),
            }
          }),
        }
      }), d.productRange.categories),
    },
    stats: {
      badge: str(statsWrapper.badge, d.stats.badge),
      badgeIcon: d.stats.badgeIcon,
      description: str(statsWrapper.description, d.stats.description),
      stats: withFallback(statRows.map(
        (row): SaflStatCardData => {
          return {
            number: str(row.number),
            suffix: str(row.suffix),
            description: str(row.description),
            vector: media(row.vector_9x8),
          }
        },
      ), d.stats.stats),
    },
    process: {
      badge: str(processWrapper.badge, d.process.badge),
      badgeIcon: d.process.badgeIcon,
      steps: withFallback(stepRows.map(
        (row): SaflProcessStepData => {
        return {
          title: str(row.title),
          description: str(row.description),
          image: media(row.image_3x2) || processImage,
        }
        },
      ), d.process.steps),
    },
  }
}
