import type { JSX } from "react"
import { notFound } from "next/navigation"

import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { getCoursePlanById } from "@/modules/course-plans/data-access"
import { CoursePlanDetail } from "@/modules/course-plans/components/course-plan-detail"
import { getStudentActiveClassId } from "@/modules/classes/data-access"

export const dynamic = "force-dynamic"

export default async function ParentCoursePlanDetailPage({
  params,
}: {
  params: Promise<{ id: string }>
}): Promise<JSX.Element> {
  const ctx = await requirePermission(Permissions.COURSE_PLAN_READ)
  const { id } = await params

  // 家长视角：解析所有孩子的班级 ID，仅允许查看孩子所在班级的计划
  let classIds: string[] = []
  if (ctx.dataScope.type === "children" && ctx.dataScope.childrenIds.length > 0) {
    const results = await Promise.all(
      ctx.dataScope.childrenIds.map((sid) => getStudentActiveClassId(sid))
    )
    classIds = results.filter((cid): cid is string => cid !== null)
  }

  const plan =
    classIds.length > 0
      ? await getCoursePlanById(id, { userId: ctx.userId, isAdmin: false, classIds })
      : null

  if (!plan) notFound()

  return (
    <div className="flex h-full flex-col space-y-6 p-8">
      <CoursePlanDetail
        plan={plan}
        backHref="/parent/course-plans"
        successHref="/parent/course-plans"
      />
    </div>
  )
}
