"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 {
  generateDiagnosticReport,
  generateClassDiagnosticReport,
  getDiagnosticReports,
  getDiagnosticReportById,
  publishDiagnosticReport,
  deleteDiagnosticReport,
} from "./data-access-reports"
import {
  GenerateStudentReportSchema,
  GenerateClassReportSchema,
  PublishReportSchema,
  DeleteReportSchema,
  GetDiagnosticReportsSchema,
  GetDiagnosticReportByIdSchema,
} from "./schema"
import type { DiagnosticReportQueryParams } from "./types"

/** 生成学生个人诊断报告 */
export async function generateStudentReportAction(
  prevState: ActionState<string> | null,
  formData: FormData
): Promise<ActionState<string>> {
  try {
    const ctx = await requirePermission(Permissions.DIAGNOSTIC_MANAGE)

    const parsed = GenerateStudentReportSchema.safeParse({
      studentId: formData.get("studentId"),
      period: formData.get("period"),
    })
    if (!parsed.success) {
      return { success: false, message: "Missing studentId or period" }
    }

    const { studentId, period } = parsed.data
    const id = await generateDiagnosticReport(studentId, period, ctx.userId)
    revalidatePath("/teacher/diagnostic")
    revalidatePath(`/teacher/diagnostic/student/${studentId}`)
    return { success: true, message: "Diagnostic report generated", data: id }
  } catch (e) {
    if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
    if (e instanceof Error) return { success: false, message: e.message }
    return { success: false, message: "Unexpected error" }
  }
}

/** 生成班级诊断报告 */
export async function generateClassReportAction(
  prevState: ActionState<string> | null,
  formData: FormData
): Promise<ActionState<string>> {
  try {
    const ctx = await requirePermission(Permissions.DIAGNOSTIC_MANAGE)

    const parsed = GenerateClassReportSchema.safeParse({
      classId: formData.get("classId"),
      period: formData.get("period"),
    })
    if (!parsed.success) {
      return { success: false, message: "Missing classId or period" }
    }

    const { classId, period } = parsed.data
    const id = await generateClassDiagnosticReport(classId, period, ctx.userId)
    revalidatePath("/teacher/diagnostic")
    revalidatePath(`/teacher/diagnostic/class/${classId}`)
    return { success: true, message: "Class diagnostic report generated", data: id }
  } catch (e) {
    if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
    if (e instanceof Error) return { success: false, message: e.message }
    return { success: false, message: "Unexpected error" }
  }
}

/** 发布诊断报告 */
export async function publishReportAction(
  prevState: ActionState<string> | null,
  formData: FormData
): Promise<ActionState<string>> {
  try {
    await requirePermission(Permissions.DIAGNOSTIC_MANAGE)

    const parsed = PublishReportSchema.safeParse({
      id: formData.get("id"),
    })
    if (!parsed.success) {
      return { success: false, message: "Missing report id" }
    }

    await publishDiagnosticReport(parsed.data.id)
    revalidatePath("/teacher/diagnostic")
    return { success: true, message: "Report published" }
  } catch (e) {
    if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
    if (e instanceof Error) return { success: false, message: e.message }
    return { success: false, message: "Unexpected error" }
  }
}

/** 删除诊断报告 */
export async function deleteReportAction(
  prevState: ActionState<string> | null,
  formData: FormData
): Promise<ActionState<string>> {
  try {
    await requirePermission(Permissions.DIAGNOSTIC_MANAGE)

    const parsed = DeleteReportSchema.safeParse({
      id: formData.get("id"),
    })
    if (!parsed.success) {
      return { success: false, message: "Missing report id" }
    }

    await deleteDiagnosticReport(parsed.data.id)
    revalidatePath("/teacher/diagnostic")
    return { success: true, message: "Report deleted" }
  } catch (e) {
    if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
    if (e instanceof Error) return { success: false, message: e.message }
    return { success: false, message: "Unexpected error" }
  }
}

/** 查询诊断报告列表（读权限） */
export async function getDiagnosticReportsAction(
  params: DiagnosticReportQueryParams
): Promise<ActionState<Awaited<ReturnType<typeof getDiagnosticReports>>>> {
  try {
    await requirePermission(Permissions.DIAGNOSTIC_READ)

    const parsed = GetDiagnosticReportsSchema.safeParse(params)
    if (!parsed.success) {
      return { success: false, message: "Invalid query params" }
    }

    const reports = await getDiagnosticReports(parsed.data)
    return { success: true, data: reports }
  } catch (e) {
    if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
    if (e instanceof Error) return { success: false, message: e.message }
    return { success: false, message: "Unexpected error" }
  }
}

/** 获取诊断报告详情（读权限） */
export async function getDiagnosticReportByIdAction(
  id: string
): Promise<ActionState<Awaited<ReturnType<typeof getDiagnosticReportById>>>> {
  try {
    await requirePermission(Permissions.DIAGNOSTIC_READ)

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

    const report = await getDiagnosticReportById(parsed.data.id)
    return { success: true, data: report }
  } catch (e) {
    if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
    if (e instanceof Error) return { success: false, message: e.message }
    return { success: false, message: "Unexpected error" }
  }
}
