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

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

export type GuideCardUpsertPayload = {
  title: string
  description: string
  icon: string
  order_index?: number
  is_active?: boolean
}

export async function fetchGuideCards(
  query: GuideCardsQuery
): Promise<PaginatedResult<AdminGuideCardRecord>> {
  const response = await adminApi.get<ApiListResponse<Record<string, unknown>>>(
    '/guide-cards',
    {
      params: {
        page: query.page,
        per_page: query.perPage,
        search: query.search,
        is_active: query.is_active,
      },
    }
  )

  return normalizePaginated(response.data, normalizeGuideCard)
}

export async function fetchGuideCard(cardId: number | string) {
  const response = await adminApi.get<ApiItemResponse<Record<string, unknown>>>(
    `/guide-cards/${cardId}`
  )
  return normalizeGuideCard(unwrapItem(response))
}

export async function createGuideCard(payload: GuideCardUpsertPayload) {
  const response = await adminApi.post<
    ApiItemResponse<Record<string, unknown>>
  >('/guide-cards', payload)
  return normalizeGuideCard(unwrapItem(response))
}

export async function updateGuideCard(
  cardId: number | string,
  payload: GuideCardUpsertPayload
) {
  const response = await adminApi.put<ApiItemResponse<Record<string, unknown>>>(
    `/guide-cards/${cardId}`,
    payload
  )
  return normalizeGuideCard(unwrapItem(response))
}

export async function deleteGuideCard(cardId: number | string) {
  await adminApi.delete(`/guide-cards/${cardId}`)
}
