import { getCollection, type CollectionEntry } from "astro:content";
import { slugify } from "./slugify";

export const getServices = async () => await getCollection("service");
export const serviceTags = async () => {
  const allServices = await getServices();
  const tags = [
    ...new Set(allServices.map((i) => i.data.tag).flat()),
  ] as string[];
  const tagPromises = tags.map(async (tag) => await getTagInfo(tag));
  return Promise.all(tagPromises);
};
export const getTags = async () => {
  const allServices = await getServices();
  const tags = [
    ...new Set(allServices.map((i) => i.data.tag).flat()),
  ] as string[];
  return tags;
};

const getTagInfo = async (tag: string) => {
  const services = await servicesByTag(tag);
  return {
    tag,
    href: slugify(tag),
    services,
  };
};

export const servicesByTag = async (tag?: string) => {
  const allServices = await getServices();
  if (!tag) return allServices;
  return allServices.filter(
    (i) => i.data.tag.toLowerCase() === tag.toLowerCase()
  );
};

export const serviceBySlug = async (slug: string) => {
  const allServices = await getServices();
  return allServices.find((i) => i.slug === slug);
};
