"use server";

import { getTranslations } from "next-intl/server";
import { requirePermission, PermissionDeniedError } from "@/shared/lib/auth-guard";
import { Permissions } from "@/shared/types/permissions";
import {
  getKnowledgePointsByTextbookId,
  getKnowledgePointsByChapterId,
} from "@/modules/textbooks/data-access";
import type { ActionState } from "./types";

// 加载知识点选项（供客户端知识点选择器使用）
export async function getKnowledgePointOptionsAction(input: {
  textbookId?: string;
  chapterId?: string;
}): Promise<
  ActionState<{ options: { id: string; name: string }[] }>
> {
  const t = await getTranslations("lessonPreparation");
  try {
    await requirePermission(Permissions.LESSON_PLAN_READ);
    if (!input.textbookId) return { success: true, data: { options: [] } };

    let kps;
    if (input.chapterId) {
      kps = await getKnowledgePointsByChapterId(input.chapterId);
    } else {
      kps = await getKnowledgePointsByTextbookId(input.textbookId);
    }
    return {
      success: true,
      data: {
        options: kps.map((kp) => ({ id: kp.id, name: kp.name })),
      },
    };
  } catch (e) {
    if (e instanceof PermissionDeniedError)
      return { success: false, message: e.message };
    return { success: false, message: t("error.loadKnowledgePoints") };
  }
}
