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

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

export type StoryUpsertPayload = {
  title: string
  badge?: string | null
  content: string
  image?: string | null
  cta_text?: string | null
  cta_url?: string | null
  order_index?: number
  is_active?: boolean
}

export async function fetchStories(
  query: StoriesQuery
): Promise<PaginatedResult<AdminStoryRecord>> {
  const response = await adminApi.get<ApiListResponse<Record<string, unknown>>>(
    '/stories',
    {
      params: {
        page: query.page,
        per_page: query.perPage,
        search: query.search || undefined,
        is_active: query.is_active,
      },
    }
  )
  return normalizePaginated(response.data, normalizeStory)
}

export async function fetchStory(storyId: number | string) {
  const response = await adminApi.get<ApiItemResponse<Record<string, unknown>>>(
    `/stories/${storyId}`
  )
  return normalizeStory(unwrapItem(response))
}

export async function createStory(payload: StoryUpsertPayload) {
  const response = await adminApi.post<ApiItemResponse<Record<string, unknown>>>(
    '/stories',
    payload
  )
  return normalizeStory(unwrapItem(response))
}

export async function updateStory(
  storyId: number | string,
  payload: StoryUpsertPayload
) {
  const response = await adminApi.put<ApiItemResponse<Record<string, unknown>>>(
    `/stories/${storyId}`,
    payload
  )
  return normalizeStory(unwrapItem(response))
}

export async function deleteStory(storyId: number | string) {
  await adminApi.delete(`/stories/${storyId}`)
}
