"use server";

import { requirePermission } from "@/shared/lib/auth-guard";
import { handleActionError } from "@/shared/lib/action-utils";
import { Permissions } from "@/shared/types/permissions";
import { suggestKnowledgePoints } from "./ai-suggest";
import { suggestKnowledgePointsSchema } from "./schema";
import { translateFieldErrors } from "./lib/i18n-errors";
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 }[];
  }>
> {
  try {
    const parsed = suggestKnowledgePointsSchema.safeParse(input);
    if (!parsed.success) {
      const errors = await translateFieldErrors(parsed.error.flatten().fieldErrors);
      return { success: false, errors };
    }

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

    // P1 修复：从 unknown 安全提取 nodes 数组，显式类型标注替代隐式 any
    // Zod 已校验 doc 是 Record<string, unknown>，但 nodes 字段需运行时检查
    const doc = parsed.data.doc;
    const nodes: unknown[] = Array.isArray(doc.nodes) ? doc.nodes : [];
    const suggestions = await suggestKnowledgePoints(
      { nodes },
      parsed.data.textbookId,
      parsed.data.chapterId,
    );
    return { success: true, data: { suggestions } };
  } catch (e) {
    // P1 修复：统一使用 handleActionError 处理错误，避免手动判断 PermissionDeniedError
    return handleActionError(e);
  }
}
