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

export type SchedulesQuery = {
  page?: number
  perPage?: number
  courseId?: string
  search?: string
  status?: string
  dateFrom?: string
  dateTo?: string
}

export type ScheduleUpsertPayload = {
  course_id: number
  start_date: string
  end_date?: string | null
  location: string
  instructor?: string | null
  quota: number
  enrolled_count?: number
  price_override?: number | null
  status?: string | null
  notes?: string | null
}

export async function fetchSchedules(
  query: SchedulesQuery
): Promise<PaginatedResult<AdminScheduleRecord>> {
  const response = await adminApi.get<ApiListResponse<Record<string, unknown>>>(
    '/schedules',
    {
      params: {
        page: query.page,
        per_page: query.perPage,
        course_id: query.courseId || undefined,
        search: query.search || undefined,
        status: query.status || undefined,
        date_from: query.dateFrom || undefined,
        date_to: query.dateTo || undefined,
      },
    }
  )

  return normalizePaginated(response.data, normalizeSchedule)
}

export async function fetchSchedule(scheduleId: number | string) {
  const response = await adminApi.get<ApiItemResponse<Record<string, unknown>>>(
    `/schedules/${scheduleId}`
  )
  return normalizeSchedule(unwrapItem(response))
}

export async function createSchedule(payload: ScheduleUpsertPayload) {
  const response = await adminApi.post<
    ApiItemResponse<Record<string, unknown>>
  >('/schedules', payload)
  return normalizeSchedule(unwrapItem(response))
}

export async function updateSchedule(
  scheduleId: number | string,
  payload: ScheduleUpsertPayload
) {
  const response = await adminApi.put<ApiItemResponse<Record<string, unknown>>>(
    `/schedules/${scheduleId}`,
    payload
  )
  return normalizeSchedule(unwrapItem(response))
}

export async function deleteSchedule(scheduleId: number | string) {
  await adminApi.delete(`/schedules/${scheduleId}`)
}
