import { adminApi } from './client'
import { unwrapItem } from './helpers'
import { normalizeCategory, normalizePaginated } from './normalizers'
import type {
  AdminCategoryRecord,
  ApiItemResponse,
  ApiListResponse,
  PaginatedResult,
} from './types'

export type CategoriesQuery = {
  page?: number
  perPage?: number
  search?: string
}

export type CategoryUpsertPayload = {
  name: string
  slug?: string
  description?: string
  image?: string | null
  icon?: string | null
  is_active?: boolean
  sort_order?: number
  meta_title?: string | null
  meta_description?: string | null
}

export async function fetchCategories(
  query: CategoriesQuery
): Promise<PaginatedResult<AdminCategoryRecord>> {
  const response = await adminApi.get<ApiListResponse<Record<string, unknown>>>(
    '/categories',
    {
      params: {
        page: query.page,
        per_page: query.perPage,
        search: query.search || undefined,
      },
    }
  )

  return normalizePaginated(response.data, normalizeCategory)
}

export async function fetchCategoryOptions() {
  const response = await fetchCategories({ page: 1, perPage: 100 })
  return response.items
}

export async function fetchCategory(categoryId: number | string) {
  const response = await adminApi.get<ApiItemResponse<Record<string, unknown>>>(
    `/categories/${categoryId}`
  )
  return normalizeCategory(unwrapItem(response))
}

export async function createCategory(payload: CategoryUpsertPayload) {
  const response = await adminApi.post<
    ApiItemResponse<Record<string, unknown>>
  >('/categories', payload)
  return normalizeCategory(unwrapItem(response))
}

export async function updateCategory(
  categoryId: number | string,
  payload: CategoryUpsertPayload
) {
  const response = await adminApi.put<ApiItemResponse<Record<string, unknown>>>(
    `/categories/${categoryId}`,
    payload
  )
  return normalizeCategory(unwrapItem(response))
}

export async function deleteCategory(categoryId: number | string) {
  await adminApi.delete(`/categories/${categoryId}`)
}
