import { getCollection } from "astro:content";
import siteConfig from "../config/site.json";

const siteUrl = (
  import.meta.env.SITE_URL ||
  import.meta.env.PUBLIC_SITE_URL ||
  siteConfig.url
).replace(/\/$/, "");

export const authors = [
  {
    slug: siteConfig.author.slug,
    name: siteConfig.author.name,
    bio: siteConfig.author.bio,
    longBio: siteConfig.author.longBio,
    avatar: siteConfig.author.avatar,
    jobTitle: siteConfig.author.jobTitle,
    knowsAbout: siteConfig.author.knowsAbout || [],
    sameAs: siteConfig.author.sameAs || [],
  },
];

export const categories = [
  { slug: "guides", name: "Guides" },
  { slug: "news", name: "News" },
  { slug: "reviews", name: "Reviews" },
  { slug: "neighborhoods", name: "Neighborhoods" },
];

export const tags = [];

export const imageSrc = (image) => (typeof image === "string" ? image : image?.src);

// Keep the FULL ISO timestamp (not date-only) so posts published on the same day order by
// their real publish time, and so Article schema / sitemap / RSS get precise datePublished.
export const normalizePost = (entry) => ({
  slug: entry.id,
  ...entry.data,
  date: entry.data.date?.toISOString(),
  updated: entry.data.updated?.toISOString(),
});

export const posts = async () => (await getCollection("blog")).map(normalizePost);

export const getPost = async (slug) => (await posts()).find((post) => post.slug === slug);
export const getAuthor = (slug) => authors.find((author) => author.slug === slug);
export const getCategory = (slug) => categories.find((category) => category.slug === slug);
export const getTag = (slug) => tags.find((tag) => tag.slug === slug);
export const postsByCategory = async (slug) =>
  (await sortedPosts()).filter((post) => post.category === slug);
export const postsByTag = async (slug) =>
  (await sortedPosts()).filter((post) => post.tags.includes(slug));
export const postsByAuthor = async (slug) =>
  (await sortedPosts()).filter((post) => post.author === slug);
export const sortedPosts = async () =>
  [...(await posts())].sort((a, b) => {
    const diff = new Date(b.date) - new Date(a.date); // newest first
    return diff !== 0 ? diff : a.slug.localeCompare(b.slug); // stable tiebreaker
  });
export const featuredPost = async () => {
  const sorted = await sortedPosts();
  return sorted.find((post) => post.featured) ?? sorted[0];
};
export const popularPosts = async () => (await sortedPosts()).slice(0, 4);
export const relatedPosts = async (post, n = 3) =>
  (await sortedPosts())
    .filter((candidate) => candidate.slug !== post.slug)
    .sort((a, b) => {
      const score = (candidate) =>
        (candidate.category === post.category ? 2 : 0) +
        candidate.tags.filter((tag) => post.tags.includes(tag)).length;
      return score(b) - score(a);
    })
    .slice(0, n);

export const adjacentPosts = async (post) => {
  const sorted = await sortedPosts();
  const index = sorted.findIndex((candidate) => candidate.slug === post.slug);
  return { prev: sorted[index + 1], next: sorted[index - 1] };
};

export const formatDate = (iso) =>
  new Date(iso).toLocaleDateString("en-US", {
    year: "numeric",
    month: "long",
    day: "numeric",
  });

export const SITE = {
  name: siteConfig.name,
  description: siteConfig.description,
  tagline: siteConfig.tagline,
  url: siteUrl,
};

// ---- JSON-LD schema builders (no @context — nest these, or add @context at the top level) ----
export const organizationSchema = () => ({
  "@type": "Organization",
  "@id": `${SITE.url}/#organization`,
  name: SITE.name,
  url: `${SITE.url}/`,
  description: SITE.description,
  logo: `${SITE.url}/favicon.svg`,
});

export const websiteSchema = () => ({
  "@type": "WebSite",
  "@id": `${SITE.url}/#website`,
  name: SITE.name,
  url: `${SITE.url}/`,
  description: SITE.description,
  inLanguage: "en",
  publisher: { "@id": `${SITE.url}/#organization` },
});

export const personSchema = (author) =>
  author && {
    "@type": "Person",
    "@id": `${SITE.url}/authors/${author.slug}#person`,
    name: author.name,
    url: `${SITE.url}/authors/${author.slug}`,
    image: author.avatar,
    description: author.longBio || author.bio,
    ...(author.jobTitle ? { jobTitle: author.jobTitle } : {}),
    ...(author.knowsAbout ? { knowsAbout: author.knowsAbout } : {}),
    ...(author.sameAs ? { sameAs: author.sameAs } : {}),
  };
