import { defineCollection, z } from 'astro:content';

// Define custom date validator that handles mm/dd/yyyy format
const customDateParser = (dateString: string | Date) => {
  // If date is already a Date object, return it
  if (dateString instanceof Date) {
    return dateString;
  }
  
  // Try to parse the date as is
  let date = new Date(dateString);
  
  // Check if it's in mm/dd/yyyy format (like 04/19/2024)
  if (isNaN(date.getTime()) || typeof dateString !== 'string') {
    return new Date(0); // Return a default date
  }
  
  // For mm/dd/yyyy format, extra handling
  if (dateString.match(/^\d{2}\/\d{2}\/\d{4}$/)) {
    const [month, day, year] = dateString.split('/').map(Number);
    date = new Date(year, month - 1, day); // Month is 0-indexed in JS
  }
  
  return date;
};

// Define the base schema for all content
const baseSchema = z.object({
  title: z.string(),
  description: z.string().optional(),
  pubDate: z.union([z.string(), z.date()]).transform(customDateParser),
  updatedDate: z.union([z.string(), z.date()]).optional().transform(val => val ? customDateParser(val) : undefined),
  heroImage: z.string().optional(),
  category: z.string().optional().default('Uncategorized'),
  tags: z.array(z.string()).default([]),
  draft: z.boolean().optional().default(false),
  readTime: z.string().optional(),
  image: z.string().optional(),
  excerpt: z.string().optional(),
  author: z.string().optional(),
  github: z.string().optional(),
  live: z.string().optional(),
  technologies: z.array(z.string()).optional(),
});

// Define collections using the same base schema
const postsCollection = defineCollection({
  type: 'content',
  schema: baseSchema,
});

const configurationsCollection = defineCollection({
  type: 'content',
  schema: baseSchema,
});

const projectsCollection = defineCollection({
  type: 'content',
  schema: baseSchema,
});

const externalPostsCollection = defineCollection({
  type: 'content',
  schema: baseSchema,
});

const blogCollection = defineCollection({
  type: 'content',
  schema: baseSchema,
});

// Export the collections
export const collections = {
  'posts': postsCollection,
  'configurations': configurationsCollection,
  'projects': projectsCollection,
  'external-posts': externalPostsCollection,
  'blog': blogCollection,
};
