const { DateTime } = require("luxon");

module.exports = {
  seasonEpisodeFormat: (_, {
    episode,
    season,
    episodePrefix = "E",
    seasonPrefix = "S",
    separator = "",
    zeroPadding = 2,
    }) => {
      const episodeNumber = episode ? parseInt(episode, 10)
      .toString()
      .padStart(zeroPadding, '0') : '';
      const seasonNumber = season ? parseInt(season, 10)
          .toString()
          .padStart(zeroPadding, '0') : '';
      return `${seasonPrefix}${seasonNumber}${separator}${episodePrefix}${episodeNumber}`
    },

  findPageByTag: (tag, collections) => {
    // Split the tag to get the collection name and slug
    const [collectionName, slug] = tag.split(":");

    if (!collectionName || !slug) {
      console.error(`Invalid tag format: "${tag}". Expected format "collection:slug".`);
      return null;
    }

    // Ensure the collection exists
    const collection = collections[collectionName];
    if (!collection) {
      console.error(`Collection "${collectionName}" not found in collections.`);
      return null;
    }

    // Search for the page in the inferred collection
    // TO-DO: this logic will break once we get into season 10, since season 1 will match 1 and 10
    const matchingPage = collection.find(item => item.fileSlug.includes(slug));

    // Return the matching page (or null if not found)
    return matchingPage || null;
  },

  extractUniqueTags: (object, tagPrefix = "") => {
    // Flatten all pages into a single array of items
    let allItems
    if (object.pages) {allItems = object.pages.flat()} else { object }

    // Extract the desired property from each item
    const extractedValues = allItems
      .map(item => item.data.tags)
      .flat(); // Flatten arrays if the property contains arrays, like tags

    // Filter for unique values with the "campaign" prefix
    const uniqueValues = [...new Set(extractedValues)]
      .filter(tag => tag.startsWith(tagPrefix));

    return uniqueValues;
  },
  formatDate: (date, format = "MMMM d, yyyy") => {
    return DateTime.fromJSDate(new Date(date)).toFormat(format);
  },
  episodeNumber: (s, episode) => {
  return episode ? Number(episode) : Number(s.replace(/[^0-9]/,''))
  }
}