/**
 * M1 课标（Standards）模块 - Server Actions
 *
 * 所有 Action 必须调用 requirePermission() 进行权限校验。
 * 返回值统一采用 ActionState<T> 类型。
 */
"use server";

import { getTranslations } from "next-intl/server";
import { revalidatePath } from "next/cache";
import {
  createStandardSchema,
  updateStandardSchema,
  getStandardsParamsSchema,
  linkPlanToStandardSchema,
} from "./schema";
import {
  getStandards,
  getStandardsTree,
  getStandardById,
  createStandard,
  updateStandard,
  deactivateStandard,
  searchStandards,
  getStandardsByPlanId,
  linkPlanToStandard,
  unlinkPlanFromStandard,
} from "./data-access";
import type { Standard, StandardTreeNode, LessonPlanStandardLink } from "./types";
import type { ActionState } from "@/shared/types/action-state";
import { Permissions } from "@/shared/types/permissions";
import { getAuthContext, requirePermission } from "@/shared/lib/auth-guard";
import { handleActionError } from "@/shared/lib/action-utils";
import { safeParseWithI18n, translateFieldErrors } from "@/modules/lesson-preparation/lib/i18n-errors";

/**
 * 查询课标列表
 */
export async function getStandardsAction(
  params?: Record<string, unknown>,
): Promise<ActionState<{ items: Standard[]; tree?: StandardTreeNode[] }>> {
  try {
    await requirePermission(Permissions.STANDARD_READ);
    const t = await getTranslations("standards");
    const parseResult = getStandardsParamsSchema.safeParse(params ?? {});
    if (!parseResult.success) {
      return {
        success: false,
        message: t("error.invalidParams"),
        errors: await translateFieldErrors(parseResult.error.flatten().fieldErrors),
      };
    }

    const { asTree, ...queryParams } = parseResult.data;
    if (asTree) {
      const tree = await getStandardsTree(queryParams);
      return { success: true, data: { items: [], tree } };
    }
    const items = await getStandards(queryParams);
    return { success: true, data: { items } };
  } catch (e) {
    return handleActionError(e);
  }
}

/**
 * 获取单个课标
 */
export async function getStandardByIdAction(
  id: string,
): Promise<ActionState<{ standard: Standard }>> {
  try {
    await requirePermission(Permissions.STANDARD_READ);
    const standard = await getStandardById(id);
    if (!standard) {
      const t = await getTranslations("standards");
      return { success: false, message: t("error.notFound") };
    }
    return { success: true, data: { standard } };
  } catch (e) {
    return handleActionError(e);
  }
}

/**
 * 创建课标
 */
export async function createStandardAction(
  input: Record<string, unknown>,
): Promise<ActionState<{ standard: Standard }>> {
  try {
    await requirePermission(Permissions.STANDARD_MANAGE);
    const t = await getTranslations("standards");
    const parseResult = await safeParseWithI18n(createStandardSchema, input);
    if (!parseResult.success) return parseResult;

    const auth = await getAuthContext();
    if (!auth.userId) {
      return { success: false, message: t("error.unauthorized") };
    }
    const standard = await createStandard(parseResult.data, auth.userId);
    revalidatePath("/admin/standards");
    return { success: true, data: { standard } };
  } catch (e) {
    return handleActionError(e);
  }
}

/**
 * 更新课标
 */
export async function updateStandardAction(
  input: Record<string, unknown>,
): Promise<ActionState<{ standard: Standard }>> {
  try {
    await requirePermission(Permissions.STANDARD_MANAGE);
    const t = await getTranslations("standards");
    const parseResult = await safeParseWithI18n(updateStandardSchema, input);
    if (!parseResult.success) return parseResult;

    const { id, ...patch } = parseResult.data;
    const updated = await updateStandard(id, patch);
    if (!updated) {
      return { success: false, message: t("error.notFound") };
    }
    revalidatePath("/admin/standards");
    return { success: true, data: { standard: updated } };
  } catch (e) {
    return handleActionError(e);
  }
}

/**
 * 停用课标（软删除）
 */
export async function deactivateStandardAction(id: string): Promise<ActionState<null>> {
  try {
    await requirePermission(Permissions.STANDARD_MANAGE);
    await deactivateStandard(id);
    revalidatePath("/admin/standards");
    return { success: true, data: null };
  } catch (e) {
    return handleActionError(e);
  }
}

/**
 * 搜索课标
 */
export async function searchStandardsAction(
  keyword: string,
  limit = 50,
): Promise<ActionState<{ items: Standard[] }>> {
  try {
    await requirePermission(Permissions.STANDARD_READ);
    const items = await searchStandards(keyword, limit);
    return { success: true, data: { items } };
  } catch (e) {
    return handleActionError(e);
  }
}

/**
 * 查询课案关联的课标
 */
export async function getPlanStandardsAction(
  planId: string,
): Promise<ActionState<{ links: LessonPlanStandardLink[] }>> {
  try {
    await requirePermission(Permissions.STANDARD_READ);
    const links = await getStandardsByPlanId(planId);
    return { success: true, data: { links } };
  } catch (e) {
    return handleActionError(e);
  }
}

/**
 * 关联课案与课标
 */
export async function linkPlanToStandardAction(
  input: Record<string, unknown>,
): Promise<ActionState<{ link: LessonPlanStandardLink }>> {
  try {
    await requirePermission(Permissions.STANDARD_LINK);
    const t = await getTranslations("standards");
    const parseResult = await safeParseWithI18n(linkPlanToStandardSchema, input);
    if (!parseResult.success) return parseResult;

    const auth = await getAuthContext();
    if (!auth.userId) {
      return { success: false, message: t("error.unauthorized") };
    }
    const link = await linkPlanToStandard(
      parseResult.data.planId,
      parseResult.data.standardId,
      parseResult.data.relationType,
      auth.userId,
    );
    revalidatePath(`/teacher/lesson-plans/${parseResult.data.planId}/edit`);
    return { success: true, data: { link } };
  } catch (e) {
    return handleActionError(e);
  }
}

/**
 * 取消课案与课标的关联
 */
export async function unlinkPlanFromStandardAction(
  planId: string,
  standardId: string,
): Promise<ActionState<null>> {
  try {
    await requirePermission(Permissions.STANDARD_LINK);
    await unlinkPlanFromStandard(planId, standardId);
    revalidatePath(`/teacher/lesson-plans/${planId}/edit`);
    return { success: true, data: null };
  } catch (e) {
    return handleActionError(e);
  }
}
