import { getAuthContext } from "@/shared/lib/auth-guard"
import { getDiagnosticReports } from "@/modules/diagnostic/data-access-reports"
import { ReportList } from "@/modules/diagnostic/components/report-list"
import type { DiagnosticReportType, DiagnosticReportStatus } from "@/modules/diagnostic/types"

export const dynamic = "force-dynamic"

type SearchParams = { [key: string]: string | string[] | undefined }

const getParam = (params: SearchParams, key: string) => {
  const v = params[key]
  return Array.isArray(v) ? v[0] : v
}

export default async function TeacherDiagnosticPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>
}) {
  const sp = await searchParams
  const ctx = await getAuthContext()

  const reportType = getParam(sp, "reportType")
  const status = getParam(sp, "status")

  const reports = await getDiagnosticReports({
    reportType: reportType && reportType !== "all" ? (reportType as DiagnosticReportType) : undefined,
    status: status && status !== "all" ? (status as DiagnosticReportStatus) : undefined,
  })

  // 学生角色仅查看自己的报告；其他角色查看全部
  const visibleReports =
    ctx.dataScope.type === "class_members"
      ? reports.filter((r) => r.studentId === ctx.userId)
      : reports

  return (
    <div className="h-full flex-1 flex-col space-y-8 p-8 md:flex">
      <div>
        <h2 className="text-2xl font-bold tracking-tight">Learning Diagnostic</h2>
        <p className="text-muted-foreground">
          View and manage diagnostic reports based on knowledge point mastery.
        </p>
      </div>
      <ReportList reports={visibleReports} />
    </div>
  )
}
