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

export type FaqsQuery = {
  page?: number
  perPage?: number
  category?: string
  search?: string
  is_active?: boolean
}

export type FaqUpsertPayload = {
  question: string
  answer: string
  category: string
  order_index?: number
  is_active?: boolean
}

export async function fetchFaqs(
  query: FaqsQuery
): Promise<PaginatedResult<AdminFaqRecord>> {
  const response = await adminApi.get<ApiListResponse<Record<string, unknown>>>(
    '/faqs',
    {
      params: {
        page: query.page,
        per_page: query.perPage,
        category: query.category || undefined,
        search: query.search || undefined,
        is_active: query.is_active,
      },
    }
  )

  return normalizePaginated(response.data, normalizeFaq)
}

export async function fetchFaq(faqId: number | string) {
  const response = await adminApi.get<ApiItemResponse<Record<string, unknown>>>(
    `/faqs/${faqId}`
  )
  return normalizeFaq(unwrapItem(response))
}

export async function createFaq(payload: FaqUpsertPayload) {
  const response = await adminApi.post<
    ApiItemResponse<Record<string, unknown>>
  >('/faqs', payload)
  return normalizeFaq(unwrapItem(response))
}

export async function updateFaq(
  faqId: number | string,
  payload: FaqUpsertPayload
) {
  const response = await adminApi.put<ApiItemResponse<Record<string, unknown>>>(
    `/faqs/${faqId}`,
    payload
  )
  return normalizeFaq(unwrapItem(response))
}

export async function deleteFaq(faqId: number | string) {
  await adminApi.delete(`/faqs/${faqId}`)
}
