import { defineCollection, z } from "astro:content";
import qs from "qs";

// Define a custom content collection that loads data from Strapi
const strapiPoleElementsLoader = defineCollection({
  // Async loader function that fetches data from Strapi API
  loader: async () => {
    // Get Strapi URL from environment variables or fallback to localhost
    const BASE_URL = import.meta.env.STRAPI_URL || "http://localhost:1337";
    const path = "/api/elements";
    const url = new URL(path, BASE_URL);

    // Build query parameters using qs to populate cover image data
    url.search = qs.stringify({
      populate: {
        mainImage: {
          fields: ["url", "alternativeText"],
        },
      },
    });

    try {
      // Fetch articles from Strapi
      const poleElementsData = await fetch(url.href);
      
      if (!poleElementsData.ok) {
        throw new Error(`Failed to fetch data from Strapi: ${poleElementsData.status} ${poleElementsData.statusText}`);
      }
      
      const response = await poleElementsData.json();
      const { data } = response;
      
      // Check if data is null or undefined
      if (!data) {
        throw new Error("No data received from Strapi API - the response was null or undefined");
      }
      
      // Ensure data is an array
      const dataArray = Array.isArray(data) ? data : [data];
      
      // Transform the API response into the desired data structure
      return dataArray
        .filter(item => item !== null && item !== undefined) // Filter out null/undefined items
        .map((item) => ({
          id: item.id?.toString() || "",
          name: item.name || "",
          title: item.name || "",
          description: item.description || "",
          createdAt: item.createdAt || "",
          updatedAt: item.updatedAt || "",
          publishedAt: item.publishedAt || "",
          mainImage: item.mainImage ? {
            id: Number(item.mainImage.id) || 0,
            documentId: item.mainImage.documentId || "",
            url: item.mainImage.url || "",
            alternativeText: item.mainImage.alternativeText || "",
          } : {
            id: 0,
            documentId: "",
            url: "",
            alternativeText: "",
          }
        }));
    } catch (error) {
      console.error("Error loading pole elements from Strapi:", error);
      return [];
    }
  },
  // Define the schema for type validation using Zod
  schema: z.object({
    id: z.string(),
    name: z.string(),
    title: z.string(),
    description: z.string(),
    createdAt: z.string(),
    updatedAt: z.string(),
    publishedAt: z.string(),
    mainImage: z.object({
      id: z.number(),
      documentId: z.string(),
      url: z.string(),
      alternativeText: z.string(),
    }),
  }),
});

export default strapiPoleElementsLoader; 