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"],
        },
      },
    });

    // Fetch articles from Strapi
    const poleElementsData = await fetch(url.href);
    const { data }= await poleElementsData.json();
    
    // Transform the API response into the desired data structure
    return data.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: {
        id: Number(item.mainImage.id),
        documentId: item.mainImage.documentId,
        url: item.mainImage.url,
        alternativeText: item.mainImage.alternativeText,
      }
    }));
  },
  // 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; 