import type { JSX } from "react"
import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { getParam, type SearchParams } from "@/shared/lib/search-params"
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"

const VALID_REPORT_TYPES: ReadonlySet<string> = new Set([
  "individual",
  "class",
  "grade",
])

const VALID_REPORT_STATUSES: ReadonlySet<string> = new Set([
  "draft",
  "published",
  "archived",
])

function parseReportType(v?: string): DiagnosticReportType | undefined {
  return v && VALID_REPORT_TYPES.has(v) ? (v as DiagnosticReportType) : undefined
}

function parseReportStatus(v?: string): DiagnosticReportStatus | undefined {
  return v && VALID_REPORT_STATUSES.has(v) ? (v as DiagnosticReportStatus) : undefined
}

export default async function TeacherDiagnosticPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>
}): Promise<JSX.Element> {
  const sp = await searchParams
  const ctx = await requirePermission(Permissions.DIAGNOSTIC_READ)

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

  const reports = await getDiagnosticReports({
    reportType: reportType && reportType !== "all" ? parseReportType(reportType) : undefined,
    status: status && status !== "all" ? parseReportStatus(status) : 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>
        <h1 className="text-2xl font-bold tracking-tight">Learning Diagnostic</h1>
        <p className="text-muted-foreground">
          View and manage diagnostic reports based on knowledge point mastery.
        </p>
      </div>
      <ReportList reports={visibleReports} />
    </div>
  )
}
