import type { JSX } from "react"
import { getElectiveCourses } from "@/modules/elective/data-access"
import { ElectiveCourseList } from "@/modules/elective/components/elective-course-list"
import { getSearchParam, type SearchParams } from "@/shared/lib/utils"
import type { ElectiveCourseStatus } from "@/modules/elective/types"

const isValidStatus = (v?: string): v is ElectiveCourseStatus =>
  v === "draft" || v === "open" || v === "closed" || v === "cancelled"

/**
 * 管理员课程列表 - 异步 RSC loader
 * 独立 Suspense 边界，可流式渲染
 * 过滤逻辑（status）在本 loader 内完成，保持组件纯净
 */
export async function CourseListLoader({
  searchParams,
}: {
  searchParams: Promise<SearchParams>
}): Promise<JSX.Element> {
  const sp = await searchParams
  const statusParam = getSearchParam(sp, "status")
  const status = isValidStatus(statusParam) ? statusParam : undefined

  const courses = await getElectiveCourses({ status })

  return (
    <ElectiveCourseList
      courses={courses}
      canManage
      createHref="/admin/elective/create"
      editBaseHref="/admin/elective"
    />
  )
}
