import { notFound } from "next/navigation"
import type { JSX } from "react"
import { getTranslations } from "next-intl/server"

import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { getElectiveCourseById } from "@/modules/elective/data-access"
import { getGrades, getStaffOptions, getSubjectOptions } from "@/modules/school/data-access"
import { ElectiveCourseForm } from "@/modules/elective/components/elective-course-form"

export const dynamic = "force-dynamic"

export default async function TeacherEditElectiveCoursePage({
  params,
}: {
  params: Promise<{ id: string }>
}): Promise<JSX.Element> {
  const t = await getTranslations("elective")
  const ctx = await requirePermission(Permissions.ELECTIVE_MANAGE)
  const { id } = await params

  const [course, subjects, grades, teachers] = await Promise.all([
    getElectiveCourseById(id),
    getSubjectOptions(),
    getGrades(),
    getStaffOptions(),
  ])

  if (!course) notFound()

  // 教师只能编辑自己教授的课程（防止跨教师越权编辑）
  if (course.teacherId && course.teacherId !== ctx.userId) {
    notFound()
  }

  return (
    <div className="flex h-full flex-col space-y-8 p-8">
      <div>
        <h2 className="text-2xl font-bold tracking-tight">{t("title.edit")}</h2>
        <p className="text-muted-foreground">{t("description.edit")}</p>
      </div>
      <ElectiveCourseForm
        mode="edit"
        course={course}
        subjects={subjects}
        grades={grades.map((g) => ({ id: g.id, name: g.name }))}
        teachers={teachers.map((teacher) => ({ id: teacher.id, name: teacher.name }))}
        backHref="/teacher/elective"
      />
    </div>
  )
}
