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

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

export type HeroSlideUpsertPayload = {
  title: string
  subtitle?: string | null
  label?: string | null
  description?: string | null
  button_text?: string | null
  button_url?: string | null
  media_type?: 'image' | 'video'
  image?: string | null
  mobile_image?: string | null
  video_url?: string | null
  order_index?: number
  is_active?: boolean
}

export async function fetchHeroSlides(
  query: HeroSlidesQuery
): Promise<PaginatedResult<AdminHeroSlideRecord>> {
  const response = await adminApi.get<ApiListResponse<Record<string, unknown>>>(
    '/hero-slides',
    {
      params: {
        page: query.page,
        per_page: query.perPage,
        search: query.search || undefined,
        is_active: query.is_active !== undefined ? query.is_active : undefined,
      },
    }
  )

  return normalizePaginated(response.data, normalizeHeroSlide)
}

export async function fetchHeroSlide(slideId: number | string) {
  const response = await adminApi.get<ApiItemResponse<Record<string, unknown>>>(
    `/hero-slides/${slideId}`
  )
  return normalizeHeroSlide(unwrapItem(response))
}

export async function createHeroSlide(payload: HeroSlideUpsertPayload) {
  const response = await adminApi.post<
    ApiItemResponse<Record<string, unknown>>
  >('/hero-slides', payload)
  return normalizeHeroSlide(unwrapItem(response))
}

export async function updateHeroSlide(
  slideId: number | string,
  payload: HeroSlideUpsertPayload
) {
  const response = await adminApi.put<ApiItemResponse<Record<string, unknown>>>(
    `/hero-slides/${slideId}`,
    payload
  )
  return normalizeHeroSlide(unwrapItem(response))
}

export async function deleteHeroSlide(slideId: number | string) {
  await adminApi.delete(`/hero-slides/${slideId}`)
}
