"use server";

import { requirePermission } from "@/shared/lib/auth-guard";
import { handleActionError } from "@/shared/lib/action-utils";
import { Permissions } from "@/shared/types/permissions";
import { fetchExternalQuestions } from "./services/external-questions-bridge";
import type { ActionState } from "./types";
import type { QuestionPickerItem, QuestionPickerParams } from "./providers/lesson-plan-provider";

/**
 * 题库查询 Server Action（V4 P0-4 修复）。
 *
 * question-bank-picker 不再直接调用 questions 模块的 Server Action，
 * 而是通过本 Action 调用 `external-questions-bridge`（data-access → data-access 合规）。
 *
 * 权限：备课模块的 LESSON_PLAN_READ 即可访问题库 picker，
 * 题库本身的细粒度权限由 questions/data-access 在返回数据时隐式遵守（仅返回公开题库）。
 */
export async function getQuestionsForPickerAction(
  params: QuestionPickerParams,
): Promise<ActionState<{ data: QuestionPickerItem[] }>> {
  try {
    await requirePermission(Permissions.LESSON_PLAN_READ);
    const res = await fetchExternalQuestions(params);
    if (res.success && res.data) {
      return { success: true, data: res.data };
    }
    return { success: false, message: res.message };
  } catch (e) {
    return handleActionError(e);
  }
}
