"use server";

import { requirePermission } from "@/shared/lib/auth-guard";
import { handleActionError } from "@/shared/lib/action-utils";
import { Permissions } from "@/shared/types/permissions";
import {
  getKnowledgePointsByTextbookId,
  getKnowledgePointsByChapterId,
} from "@/modules/textbooks/data-access";
import { getKnowledgePointOptionsSchema } from "./schema";
import { translateFieldErrors } from "./lib/i18n-errors";
import type { ActionState } from "./types";

// 知识点选项类型（P1 修复：显式类型标注替代隐式 any）
type KnowledgePointOption = { id: string; name: string };

// 加载知识点选项（供客户端知识点选择器使用）
export async function getKnowledgePointOptionsAction(input: {
  textbookId?: string;
  chapterId?: string;
}): Promise<
  ActionState<{ options: KnowledgePointOption[] }>
> {
  try {
    const parsed = getKnowledgePointOptionsSchema.safeParse(input);
    if (!parsed.success) {
      const errors = await translateFieldErrors(parsed.error.flatten().fieldErrors);
      return { success: false, errors };
    }

    await requirePermission(Permissions.LESSON_PLAN_READ);
    if (!parsed.data.textbookId) return { success: true, data: { options: [] } };

    // P1 修复：显式类型标注替代 `let kps;` 隐式 any
    let kps: KnowledgePointOption[];
    if (parsed.data.chapterId) {
      kps = await getKnowledgePointsByChapterId(parsed.data.chapterId);
    } else {
      kps = await getKnowledgePointsByTextbookId(parsed.data.textbookId);
    }
    return {
      success: true,
      data: {
        options: kps.map((kp) => ({ id: kp.id, name: kp.name })),
      },
    };
  } catch (e) {
    // P1 修复：统一使用 handleActionError 处理错误
    return handleActionError(e);
  }
}
