// src/pages/search-index.json.js
// Generates a JSON file with content from all collections for site-wide search

import { getCollection } from 'astro:content';

export async function get() {
  // Get content from all collections
  const posts = await getCollection('posts', ({ data }) => {
    // Exclude draft posts in production
    return import.meta.env.PROD ? !data.draft : true;
  }).catch(() => []);
  
  const projects = await getCollection('projects').catch(() => []);
  const configurations = await getCollection('configurations').catch(() => []);
  const externalPosts = await getCollection('external-posts').catch(() => []);
  
  // Transform posts into search-friendly format
  const searchablePosts = posts.map(post => ({
    slug: post.slug,
    title: post.data.title,
    description: post.data.description || '',
    pubDate: post.data.pubDate ? new Date(post.data.pubDate).toISOString() : '',
    category: post.data.category || 'Uncategorized',
    tags: post.data.tags || [],
    readTime: post.data.readTime || '5 min read',
    type: 'post',
    url: `/posts/${post.slug}/`
  }));
  
  // Transform projects
  const searchableProjects = projects.map(project => ({
    slug: project.slug,
    title: project.data.title,
    description: project.data.description || '',
    pubDate: project.data.pubDate ? new Date(project.data.pubDate).toISOString() : '',
    category: project.data.category || 'Projects',
    tags: project.data.tags || [],
    type: 'project',
    url: `/projects/${project.slug}/`
  }));
  
  // Transform configurations
  const searchableConfigurations = configurations.map(config => ({
    slug: config.slug,
    title: config.data.title,
    description: config.data.description || '',
    pubDate: config.data.pubDate ? new Date(config.data.pubDate).toISOString() : '',
    category: config.data.category || 'Configurations',
    tags: config.data.tags || [],
    type: 'configuration',
    url: `/configurations/${config.slug}/`
  }));
  
  // Transform external posts
  const searchableExternalPosts = externalPosts.map(post => ({
    slug: post.slug,
    title: post.data.title,
    description: post.data.description || '',
    pubDate: post.data.pubDate ? new Date(post.data.pubDate).toISOString() : '',
    category: post.data.category || 'External',
    tags: post.data.tags || [],
    type: 'external',
    url: post.data.url // Use the external URL directly
  }));
  
  // Combine all searchable content
  const allSearchableContent = [
    ...searchablePosts,
    ...searchableProjects,
    ...searchableConfigurations,
    ...searchableExternalPosts
  ];
  
  // Return JSON
  return {
    body: JSON.stringify(allSearchableContent),
    headers: {
      'Content-Type': 'application/json',
      'Cache-Control': 'max-age=3600'
    }
  };
}