/**
 * Blog API utilities
 * Helper functions for fetching blog posts and categories from Payload CMS
 */

interface PostImage {
  url: string
  alt?: string
}

export interface Category {
  id: string
  title: string
  slug: string
  backgroundColor?: string
  textColor?: string
  nameEn?: string
}

export interface Post {
  id: string
  title: string
  slug: string
  heroImage?: PostImage | null
  ogImage?: PostImage | null
  excerpt?: string | null
  content?: any
  categories?: Category[] | null
  relatedPosts?: Post[] | null
  publishedAt?: string | null
  createdAt?: string | null
  updatedAt?: string | null
  status?: string
  meta?: {
    title?: string
    description?: string
    image?: PostImage
  }
}

export interface BlogResponse {
  docs: Post[]
  totalDocs: number
  totalPages: number
  page: number
  hasPreviousPage: boolean
  hasNextPage: boolean
}

// Use production CMS API (enchun-cms.anlstudio.cc) for all environments
// Production CMS has 35+ published posts with proper slugs
const PAYLOAD_API_URL = 'https://enchun-cms.anlstudio.cc/api'

/**
 * Fetch published posts from Payload CMS
 */
export async function fetchPosts(
  page = 1,
  limit = 12,
  categorySlug?: string | null
): Promise<BlogResponse> {
  try {
    // Build query parameters
    const params = new URLSearchParams()

    if (categorySlug) {
      // For category filtering, we need to filter by category
      params.append('where[categories][slug][equals]', categorySlug)
    }
    // Always filter by published status (use _status for Payload's internal status)
    params.append('where[_status][equals]', 'published')

    params.append('sort', '-publishedAt')
    params.append('limit', limit.toString())
    params.append('page', page.toString())
    params.append('depth', '1')

    const response = await fetch(`${PAYLOAD_API_URL}/posts?${params}`)

    if (!response.ok) {
      throw new Error(`Failed to fetch posts: ${response.statusText}`)
    }

    const data = await response.json()
    return data as BlogResponse
  } catch (error) {
    console.error('Error fetching posts:', error)
    return {
      docs: [],
      totalDocs: 0,
      totalPages: 0,
      page: 1,
      hasPreviousPage: false,
      hasNextPage: false
    }
  }
}

/**
 * Fetch a single post by slug
 */
export async function fetchPostBySlug(slug: string): Promise<Post | null> {
  try {
    const params = new URLSearchParams()
    params.append('where[slug][equals]', slug)
    params.append('where[_status][equals]', 'published')
    params.append('depth', '2')

    const response = await fetch(`${PAYLOAD_API_URL}/posts?${params}`)

    if (!response.ok) {
      throw new Error(`Failed to fetch post: ${response.statusText}`)
    }

    const data = await response.json()
    return data.docs?.[0] || null
  } catch (error) {
    console.error('Error fetching post by slug:', error)
    return null
  }
}

/**
 * Fetch all categories
 */
export async function fetchCategories(): Promise<Category[]> {
  try {
    const response = await fetch(`${PAYLOAD_API_URL}/categories?sort=order&limit=20&depth=0`)

    if (!response.ok) {
      throw new Error(`Failed to fetch categories: ${response.statusText}`)
    }

    const data = await response.json()
    return data.docs || []
  } catch (error) {
    console.error('Error fetching categories:', error)
    return []
  }
}

/**
 * Fetch category by slug
 */
export async function fetchCategoryBySlug(slug: string): Promise<Category | null> {
  try {
    const response = await fetch(`${PAYLOAD_API_URL}/categories?where[slug][equals]=${slug}&depth=0`)

    if (!response.ok) {
      throw new Error(`Failed to fetch category: ${response.statusText}`)
    }

    const data = await response.json()
    return data.docs?.[0] || null
  } catch (error) {
    console.error('Error fetching category by slug:', error)
    return null
  }
}

/**
 * Fetch related posts (same category, excluding current post)
 */
export async function fetchRelatedPosts(
  currentPostId: string,
  categorySlugs: string[],
  limit = 3
): Promise<Post[]> {
  try {
    if (categorySlugs.length === 0) return []

    // Use a simpler approach - fetch published posts and filter
    const params = new URLSearchParams()
    params.append('where[_status][equals]', 'published')
    params.append('limit', '20') // Fetch more to filter client-side
    params.append('sort', '-publishedAt')
    params.append('depth', '1')

    const response = await fetch(`${PAYLOAD_API_URL}/posts?${params}`)

    if (!response.ok) {
      throw new Error(`Failed to fetch related posts: ${response.statusText}`)
    }

    const data = await response.json()
    const allPosts = data.docs || []

    // Filter: same category, exclude current, limit
    return allPosts
      .filter((post: Post) => post.id !== currentPostId)
      .filter((post: Post) =>
        post.categories?.some((cat: Category) => categorySlugs.includes(cat.slug))
      )
      .slice(0, limit)
  } catch (error) {
    console.error('Error fetching related posts:', error)
    return []
  }
}

/**
 * Format date in Traditional Chinese
 */
export function formatDate(dateStr: string | null | undefined): string {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-TW', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}
