/**
 * Portfolio API utilities
 * Helper functions for fetching portfolio items from Payload CMS
 */

interface PortfolioImage {
  url: string
  alt?: string
}

export interface PortfolioTag {
  id: string
  tag: string
}

export interface PortfolioItem {
  id: string
  title: string
  slug: string
  url?: string | null
  image?: PortfolioImage | null
  description?: string | null
  websiteType?: 'corporate' | 'ecommerce' | 'landing' | 'brand' | 'other' | null
  tags?: PortfolioTag[] | null
  createdAt?: string | null
  updatedAt?: string | null
}

export interface PortfolioResponse {
  docs: PortfolioItem[]
  totalDocs: number
  totalPages: number
  page: number
  hasPreviousPage: boolean
  hasNextPage: boolean
}

// Use production CMS API (enchun-cms.anlstudio.cc) for all environments
const PAYLOAD_API_URL = 'https://enchun-cms.anlstudio.cc/api'

/**
 * Fetch all portfolio items
 */
export async function fetchPortfolios(
  page = 1,
  limit = 100
): Promise<PortfolioResponse> {
  try {
    const params = new URLSearchParams({
      sort: '-createdAt',
      limit: limit.toString(),
      page: page.toString(),
      depth: '1'
    })

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

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

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

/**
 * Fetch a single portfolio item by slug
 */
export async function fetchPortfolioBySlug(slug: string): Promise<PortfolioItem | null> {
  try {
    const response = await fetch(`${PAYLOAD_API_URL}/portfolio?where[slug][equals]=${slug}&depth=1`)

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

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

/**
 * Get website type label in Traditional Chinese
 */
export function getWebsiteTypeLabel(type: string | null | undefined): string {
  const labels: Record<string, string> = {
    corporate: '企業官網',
    ecommerce: '電商網站',
    landing: '活動頁面',
    brand: '品牌網站',
    other: '其他'
  }
  return labels[type || ''] || '其他'
}

/**
 * Get all tags from portfolio items
 */
export function getAllTags(portfolios: PortfolioItem[]): string[] {
  const tagSet = new Set<string>()
  portfolios.forEach(item => {
    item.tags?.forEach(tagObj => {
      tagSet.add(tagObj.tag)
    })
  })
  return Array.from(tagSet).sort()
}

/**
 * Filter portfolios by website type
 */
export function filterByType(portfolios: PortfolioItem[], type: string): PortfolioItem[] {
  if (!type || type === 'all') return portfolios
  return portfolios.filter(item => item.websiteType === type)
}

/**
 * Filter portfolios by tag
 */
export function filterByTag(portfolios: PortfolioItem[], tag: string): PortfolioItem[] {
  if (!tag) return portfolios
  return portfolios.filter(item =>
    item.tags?.some(tagObj => tagObj.tag === tag)
  )
}
