"use server"

import { revalidatePath } from "next/cache"
import { requirePermission, PermissionDeniedError } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"

import type { ActionState } from "@/shared/types/action-state"
import {
  createTeacherClass,
  deleteTeacherClass,
  updateTeacherClass,
} from "./data-access"
import { findGradeIdByHeadAndName, isGradeHead } from "@/modules/school/data-access"
import {
  CreateTeacherClassSchema,
  UpdateTeacherClassSchema,
  DeleteTeacherClassSchema,
} from "./schema"
import { hasAdminScope } from "./actions-shared"

export async function createTeacherClassAction(
  prevState: ActionState<string> | null,
  formData: FormData
): Promise<ActionState<string>> {
  try {
    const ctx = await requirePermission(Permissions.CLASS_CREATE)

    const parsed = CreateTeacherClassSchema.safeParse({
      name: formData.get("name"),
      grade: formData.get("grade"),
      schoolName: formData.get("schoolName"),
      schoolId: formData.get("schoolId"),
      gradeId: formData.get("gradeId"),
      homeroom: formData.get("homeroom"),
      room: formData.get("room"),
    })
    if (!parsed.success) {
      return { success: false, message: "Class name and grade are required" }
    }

    const { name, grade, schoolName, schoolId, gradeId, homeroom, room } = parsed.data

    // P1-1: 使用 dataScope 替代 ctx.roles.includes("admin") 硬编码
    if (!hasAdminScope(ctx)) {
      const userId = ctx.userId

      const normalizedGradeId = typeof gradeId === "string" ? gradeId.trim() : ""
      const isOwner = normalizedGradeId
        ? await isGradeHead(normalizedGradeId, userId)
        : Boolean(await findGradeIdByHeadAndName(userId, grade))
      if (!isOwner) {
        return { success: false, message: "Only admins and grade heads can create classes" }
      }
    }

    try {
      const id = await createTeacherClass({
        schoolName: schoolName ?? null,
        schoolId: schoolId ?? null,
        name,
        grade,
        gradeId: gradeId ?? null,
        homeroom: homeroom ?? null,
        room: room ?? null,
      })
      revalidatePath("/teacher/classes/my")
      revalidatePath("/teacher/classes/students")
      revalidatePath("/teacher/classes/schedule")
      return { success: true, message: "Class created successfully", data: id }
    } catch (error) {
      return { success: false, message: error instanceof Error ? error.message : "Failed to create class" }
    }
  } catch (e) {
    if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
    throw e
  }
}

export async function updateTeacherClassAction(
  classId: string,
  prevState: ActionState | null,
  formData: FormData
): Promise<ActionState> {
  try {
    await requirePermission(Permissions.CLASS_UPDATE)

    const parsed = UpdateTeacherClassSchema.safeParse({
      classId,
      schoolName: formData.get("schoolName"),
      schoolId: formData.get("schoolId"),
      name: formData.get("name"),
      grade: formData.get("grade"),
      gradeId: formData.get("gradeId"),
      homeroom: formData.get("homeroom"),
      room: formData.get("room"),
    })
    if (!parsed.success) {
      return { success: false, message: "Missing class id" }
    }

    const { classId: validatedClassId, schoolName, schoolId, name, grade, gradeId, homeroom, room } = parsed.data

    try {
      await updateTeacherClass(validatedClassId, {
        schoolName: schoolName ?? undefined,
        schoolId: schoolId ?? undefined,
        name: name ?? undefined,
        grade: grade ?? undefined,
        gradeId: gradeId ?? undefined,
        homeroom: homeroom ?? undefined,
        room: room ?? undefined,
      })
      revalidatePath("/teacher/classes/my")
      revalidatePath("/teacher/classes/students")
      revalidatePath("/teacher/classes/schedule")
      return { success: true, message: "Class updated successfully" }
    } catch (error) {
      return { success: false, message: error instanceof Error ? error.message : "Failed to update class" }
    }
  } catch (e) {
    if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
    throw e
  }
}

export async function deleteTeacherClassAction(classId: string): Promise<ActionState> {
  try {
    await requirePermission(Permissions.CLASS_DELETE)

    const parsed = DeleteTeacherClassSchema.safeParse({ classId })
    if (!parsed.success) {
      return { success: false, message: "Missing class id" }
    }

    try {
      await deleteTeacherClass(parsed.data.classId)
      revalidatePath("/teacher/classes/my")
      revalidatePath("/teacher/classes/students")
      revalidatePath("/teacher/classes/schedule")
      return { success: true, message: "Class deleted successfully" }
    } catch (error) {
      return { success: false, message: error instanceof Error ? error.message : "Failed to delete class" }
    }
  } catch (e) {
    if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
    throw e
  }
}
