"use server";

import { getTranslations } from "next-intl/server";
import { requirePermission, PermissionDeniedError } from "@/shared/lib/auth-guard";
import { Permissions } from "@/shared/types/permissions";
import { suggestKnowledgePoints } from "./ai-suggest";
import { suggestKnowledgePointsSchema } from "./schema";
import type { ActionState } from "@/shared/types/action-state";

export async function suggestKnowledgePointsAction(input: {
  doc: unknown;
  textbookId?: string;
  chapterId?: string;
}): Promise<
  ActionState<{
    suggestions: { id: string; name: string; reason: string }[];
  }>
> {
  const t = await getTranslations("lessonPreparation");
  try {
    const parsed = suggestKnowledgePointsSchema.safeParse(input);
    if (!parsed.success) {
      return { success: false, errors: parsed.error.flatten().fieldErrors };
    }

    // 并行校验两个权限点
    await Promise.all([
      requirePermission(Permissions.LESSON_PLAN_READ),
      requirePermission(Permissions.AI_CHAT),
    ]);

    // 从 unknown 安全提取 nodes 数组：Zod 已校验 doc 是对象
    const doc = parsed.data.doc;
    const nodes = Array.isArray(doc.nodes) ? doc.nodes : [];
    const suggestions = await suggestKnowledgePoints(
      { nodes },
      parsed.data.textbookId,
      parsed.data.chapterId,
    );
    return { success: true, data: { suggestions } };
  } catch (e) {
    if (e instanceof PermissionDeniedError)
      return { success: false, message: e.message };
    return { success: false, message: t("error.aiSuggest") };
  }
}
