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

export type CoursesQuery = {
  page?: number
  perPage?: number
  search?: string
  category?: string
  sort?: string
}

export type CourseUpsertPayload = {
  category_id: number
  slug: string
  title: string
  sub?: string | null
  desc: string
  long_desc: string
  duration: string
  badge?: string | null
  image?: string | null
  price?: string | null
  includes?: string[]
  requirements?: string[]
  meta_title?: string | null
  meta_description?: string | null
  scope?: string[]
  standard?: string | null
  location?: string | null
}

export async function fetchCourses(
  query: CoursesQuery
): Promise<PaginatedResult<AdminCourseRecord>> {
  const response = await adminApi.get<ApiListResponse<Record<string, unknown>>>(
    '/courses',
    {
      params: {
        page: query.page,
        per_page: query.perPage,
        search: query.search || undefined,
        category: query.category || undefined,
        sort: query.sort || undefined,
      },
    }
  )

  return normalizePaginated(response.data, normalizeCourse)
}

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

export async function fetchCourse(courseId: number | string) {
  const response = await adminApi.get<ApiItemResponse<Record<string, unknown>>>(
    `/courses/${courseId}`
  )
  return normalizeCourse(unwrapItem(response))
}

export async function createCourse(payload: CourseUpsertPayload) {
  const response = await adminApi.post<
    ApiItemResponse<Record<string, unknown>>
  >('/courses', payload)
  return normalizeCourse(unwrapItem(response))
}

export async function updateCourse(
  courseId: number | string,
  payload: CourseUpsertPayload
) {
  const response = await adminApi.put<ApiItemResponse<Record<string, unknown>>>(
    `/courses/${courseId}`,
    payload
  )
  return normalizeCourse(unwrapItem(response))
}

export async function deleteCourse(courseId: number | string) {
  await adminApi.delete(`/courses/${courseId}`)
}
