import { apiClient } from './api-client'

const WP_URL = import.meta.env.VITE_WP_API_URL || 'https://panel.profbody.uz/wp-json/wp/v2'

export interface WpPost {
  id: number
  date: string
  title: { rendered: string }
  content: { rendered: string }
  excerpt: { rendered: string }
  featured_media: number
  categories?: number[]
  _embedded?: {
    'wp:featuredmedia'?: Array<{
      source_url: string
      alt_text: string
    }>
    'wp:term'?: Array<Array<{
      id: number
      name: string
      slug: string
      taxonomy: string
    }>>
  }
}

export interface WpCategory {
  id: number
  count: number
  description: string
  link: string
  name: string
  slug: string
  taxonomy: string
  parent: number
}

export const wordpressService = {
  /**
   * Fetch latest posts с поддержкой nprogress
   */
  async getPosts(params: Record<string, any> = {}): Promise<WpPost[]> {
    const query = new URLSearchParams({
      _embed: '1',
      per_page: '10',
      ...params
    }).toString()

    return apiClient.fetch<WpPost[]>(`${WP_URL}/posts?${query}`)
  },

  /**
   * Fetch posts by category ID
   */
  async getPostsByCategory(categoryId: number, params: Record<string, any> = {}): Promise<WpPost[]> {
    const query = new URLSearchParams({
      _embed: '1',
      categories: categoryId.toString(),
      per_page: '10',
      ...params
    }).toString()

    return apiClient.fetch<WpPost[]>(`${WP_URL}/posts?${query}`)
  },

  /**
   * Fetch a single post by slug с поддержкой nprogress
   */
  async getPostBySlug(slug: string): Promise<WpPost | null> {
    const posts = await apiClient.fetch<WpPost[]>(`${WP_URL}/posts?slug=${slug}&_embed=1`)
    return posts.length > 0 ? posts[0] : null
  },

  /**
   * Fetch pages с поддержкой nprogress
   */
  async getPages(params: Record<string, any> = {}): Promise<WpPost[]> {
    const query = new URLSearchParams({
      _embed: '1',
      ...params
    }).toString()

    return apiClient.fetch<WpPost[]>(`${WP_URL}/pages?${query}`)
  },

  /**
   * Fetch a single page by slug с поддержкой nprogress
   */
  async getPageBySlug(slug: string): Promise<WpPost | null> {
    const pages = await apiClient.fetch<WpPost[]>(`${WP_URL}/pages?slug=${slug}&_embed=1`)
    return pages.length > 0 ? pages[0] : null
  },

  /**
   * Fetch all categories
   */
  async getCategories(params: Record<string, any> = {}): Promise<WpCategory[]> {
    const query = new URLSearchParams(params).toString()
    return apiClient.fetch<WpCategory[]>(`${WP_URL}/categories?${query}`)
  },

  /**
   * Fetch category by ID
   */
  async getCategoryById(categoryId: number): Promise<WpCategory | null> {
    try {
      const categories = await apiClient.fetch<WpCategory[]>(`${WP_URL}/categories?include=${categoryId}`)
      return categories.length > 0 ? categories[0] : null
    } catch (error) {
      console.error(`Error fetching category ${categoryId}:`, error)
      return null
    }
  }
}
