"use server";

import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { getTranslations } from "next-intl/server";
import { requirePermission } from "@/shared/lib/auth-guard";
import { Permissions } from "@/shared/types/permissions";
import { handleActionError } from "@/shared/lib/action-utils";
import {
  getLessonPlans,
  getLessonPlanById,
  createLessonPlan,
  updateLessonPlanContent,
  softDeleteLessonPlan,
  publishLessonPlan,
  unpublishLessonPlan,
  duplicateLessonPlan,
  getTextbooksForPicker,
  getChaptersForPicker,
  LessonPlanDataError,
  normalizeDocument,
} from "./data-access";
import {
  getLessonPlanVersions,
  createLessonPlanVersion,
  revertToVersion,
  pruneAutoVersions,
} from "./data-access-versions";
import {
  getLessonPlanTemplates,
  saveAsTemplate,
  deletePersonalTemplate,
} from "./data-access-templates";
import {
  createLessonPlanSchema,
  updateLessonPlanContentSchema,
  saveVersionSchema,
  revertVersionSchema,
  saveAsTemplateSchema,
  getLessonPlansParamsSchema,
} from "./schema";
import { translateFieldErrors } from "./lib/i18n-errors";
import type { ActionState, LessonPlan, LessonPlanDocument } from "./types";

// ---- 课案列表 ----
// P0-7 修复：params 使用 Zod 验证，防止畸形输入和 LIKE 注入
export async function getLessonPlansAction(params: {
  query?: string;
  textbookId?: string;
  chapterId?: string;
  subjectId?: string;
  status?: string;
}): Promise<
  ActionState<{
    items: Awaited<ReturnType<typeof getLessonPlans>>;
  }>
> {
  try {
    const ctx = await requirePermission(Permissions.LESSON_PLAN_READ);
    const parsed = getLessonPlansParamsSchema.safeParse(params);
    if (!parsed.success) {
      const errors = await translateFieldErrors(parsed.error.flatten().fieldErrors);
      return { success: false, errors };
    }
    const items = await getLessonPlans(parsed.data, ctx.dataScope, ctx.userId);
    return { success: true, data: { items } };
  } catch (e) {
    return handleActionError(e);
  }
}

// ---- 单课案 ----
export async function getLessonPlanByIdAction(
  planId: string,
): Promise<ActionState<{ plan: LessonPlan }>> {
  const t = await getTranslations("lessonPreparation");
  try {
    const ctx = await requirePermission(Permissions.LESSON_PLAN_READ);
    const plan = await getLessonPlanById(planId, ctx.userId);
    if (!plan) return { success: false, message: t("error.notFound") };
    return { success: true, data: { plan } };
  } catch (e) {
    return handleActionError(e);
  }
}

// ---- 创建 ----
export async function createLessonPlanAction(
  prevState: ActionState | null,
  formData: FormData,
): Promise<ActionState<{ planId: string }>> {
  const t = await getTranslations("lessonPreparation");
  try {
    const ctx = await requirePermission(Permissions.LESSON_PLAN_CREATE);
    const parsed = createLessonPlanSchema.safeParse({
      title: formData.get("title"),
      textbookId: formData.get("textbookId") || undefined,
      chapterId: formData.get("chapterId") || undefined,
      subjectId: formData.get("subjectId") || undefined,
      gradeId: formData.get("gradeId") || undefined,
      templateId: formData.get("templateId"),
    });
    if (!parsed.success) {
      const errors = await translateFieldErrors(parsed.error.flatten().fieldErrors);
      return { success: false, errors };
    }
    const { planId } = await createLessonPlan({
      ...parsed.data,
      creatorId: ctx.userId,
      // V2-2 修复：传入翻译函数，将 SYSTEM_TEMPLATES 中的 i18n 键翻译为实际文本
      translateTitle: (key: string) => {
        // 支持 "blockType.objective" 和 "template.blocks.tpl_review.1" 两种键
        if (key.startsWith("blockType.")) {
          const blockKey = key.replace("blockType.", "");
          return t(`blockType.${blockKey}`);
        }
        if (key.startsWith("template.blocks.")) {
          const parts = key.split(".");
          // 期望格式：template.blocks.{templateId}.{blockIndex}
          if (parts.length < 4) return key;
          const templateId = parts[2];
          const blockIndex = parts[3];
          return t(`template.blocks.${templateId}.${blockIndex}`);
        }
        return key;
      },
    });
    revalidatePath("/teacher/lesson-plans");
    return { success: true, data: { planId } };
  } catch (e) {
    if (e instanceof LessonPlanDataError && e.code === "TEMPLATE_NOT_FOUND")
      return { success: false, message: t("error.templateNotFound") };
    return handleActionError(e);
  }
}

// ---- 更新 content（自动保存）----
export async function updateLessonPlanAction(input: {
  planId: string;
  title?: string;
  content: LessonPlanDocument;
}): Promise<ActionState> {
  try {
    const ctx = await requirePermission(Permissions.LESSON_PLAN_UPDATE);
    const parsed = updateLessonPlanContentSchema.safeParse(input);
    if (!parsed.success) {
      const errors = await translateFieldErrors(parsed.error.flatten().fieldErrors);
      return { success: false, errors };
    }
    // P1 修复：Zod 已校验 content 是 Record<string, unknown>，
    // 通过 normalizeDocument 安全转换（内部使用类型守卫），替代 as unknown as 断言
    const content = normalizeDocument(parsed.data.content);
    await updateLessonPlanContent(parsed.data.planId, ctx.userId, {
      ...(parsed.data.title ? { title: parsed.data.title } : {}),
      content,
    });
    revalidatePath("/teacher/lesson-plans");
    return { success: true };
  } catch (e) {
    return handleActionError(e);
  }
}

// ---- 手动保存版本 ----
// P0-5 修复：saveVersionSchema 现在包含 content 字段校验
export async function saveLessonPlanVersionAction(input: {
  planId: string;
  content: LessonPlanDocument;
  label?: string;
}): Promise<ActionState<{ versionNo: number }>> {
  try {
    const ctx = await requirePermission(Permissions.LESSON_PLAN_UPDATE);
    const parsed = saveVersionSchema.safeParse(input);
    if (!parsed.success) {
      const errors = await translateFieldErrors(parsed.error.flatten().fieldErrors);
      return { success: false, errors };
    }
    // P0-5 修复：使用 Zod 验证后的 content，通过 normalizeDocument 安全转换为 LessonPlanDocument
    const content = normalizeDocument(parsed.data.content);
    const version = await createLessonPlanVersion({
      planId: parsed.data.planId,
      content,
      userId: ctx.userId,
      isAuto: false,
      label: parsed.data.label,
    });
    if (!version) {
      // V4 P1-16 修复：原始字符串改为 i18n 键
      const t = await getTranslations("lessonPreparation");
      return { success: false, message: t("error.notFound") };
    }
    await pruneAutoVersions(parsed.data.planId, ctx.userId);
    return { success: true, data: { versionNo: version.versionNo } };
  } catch (e) {
    return handleActionError(e);
  }
}

// ---- 版本列表 ----
export async function getLessonPlanVersionsAction(
  planId: string,
): Promise<
  ActionState<{
    versions: Awaited<ReturnType<typeof getLessonPlanVersions>>;
  }>
> {
  try {
    const ctx = await requirePermission(Permissions.LESSON_PLAN_READ);
    const versions = await getLessonPlanVersions(planId, ctx.userId);
    return { success: true, data: { versions } };
  } catch (e) {
    return handleActionError(e);
  }
}

// ---- 回退版本 ----
export async function revertLessonPlanVersionAction(input: {
  planId: string;
  versionNo: number;
}): Promise<ActionState<{ newVersionNo: number }>> {
  const t = await getTranslations("lessonPreparation");
  try {
    const ctx = await requirePermission(Permissions.LESSON_PLAN_UPDATE);
    const parsed = revertVersionSchema.safeParse(input);
    if (!parsed.success) {
      const errors = await translateFieldErrors(parsed.error.flatten().fieldErrors);
      return { success: false, errors };
    }
    // V3 修复：传入 i18n 翻译的回退标签，避免 data-access 硬编码中文
    const revertLabel = t("version.revertLabel", { versionNo: parsed.data.versionNo });
    const result = await revertToVersion(
      parsed.data.planId,
      parsed.data.versionNo,
      ctx.userId,
      revertLabel,
    );
    if (!result) return { success: false, message: t("error.versionNotFound") };
    revalidatePath(`/teacher/lesson-plans/${parsed.data.planId}/edit`);
    return { success: true, data: { newVersionNo: result.newVersionNo } };
  } catch (e) {
    return handleActionError(e);
  }
}

// ---- 删除（软删除）----
export async function deleteLessonPlanAction(
  planId: string,
): Promise<ActionState> {
  try {
    const ctx = await requirePermission(Permissions.LESSON_PLAN_DELETE);
    await softDeleteLessonPlan(planId, ctx.userId);
    revalidatePath("/teacher/lesson-plans");
    return { success: true };
  } catch (e) {
    return handleActionError(e);
  }
}

// ---- 发布课案（P0-1 修复）----
// 发布后学生和家长可查看此课案
export async function publishLessonPlanAction(
  planId: string,
): Promise<ActionState> {
  const t = await getTranslations("lessonPreparation");
  try {
    const ctx = await requirePermission(Permissions.LESSON_PLAN_PUBLISH);
    await publishLessonPlan(planId, ctx.userId);
    revalidatePath("/teacher/lesson-plans");
    revalidatePath(`/teacher/lesson-plans/${planId}/edit`);
    return { success: true, message: t("action.publishPlanSuccess") };
  } catch (e) {
    if (e instanceof LessonPlanDataError && e.code === "NOT_FOUND")
      return { success: false, message: t("error.notFound") };
    return handleActionError(e);
  }
}

// ---- 撤回发布 ----
// 撤回后学生和家长将无法查看此课案
export async function unpublishLessonPlanAction(
  planId: string,
): Promise<ActionState> {
  const t = await getTranslations("lessonPreparation");
  try {
    const ctx = await requirePermission(Permissions.LESSON_PLAN_PUBLISH);
    await unpublishLessonPlan(planId, ctx.userId);
    revalidatePath("/teacher/lesson-plans");
    revalidatePath(`/teacher/lesson-plans/${planId}/edit`);
    return { success: true, message: t("action.unpublishPlanSuccess") };
  } catch (e) {
    if (e instanceof LessonPlanDataError && e.code === "NOT_FOUND")
      return { success: false, message: t("error.notFound") };
    return handleActionError(e);
  }
}

// ---- 复制 ----
export async function duplicateLessonPlanAction(
  planId: string,
): Promise<ActionState<{ newPlanId: string }>> {
  const t = await getTranslations("lessonPreparation");
  try {
    const ctx = await requirePermission(Permissions.LESSON_PLAN_CREATE);
    // V3 修复：传入 i18n 翻译的副本后缀，避免 data-access 硬编码中文
    const { newPlanId } = await duplicateLessonPlan(
      planId,
      ctx.userId,
      t("error.duplicateSuffix"),
    );
    revalidatePath("/teacher/lesson-plans");
    return { success: true, data: { newPlanId } };
  } catch (e) {
    if (e instanceof LessonPlanDataError && e.code === "NOT_FOUND")
      return { success: false, message: t("error.notFound") };
    return handleActionError(e);
  }
}

// V5-12 R4：表单兼容版本（从 formData 提取 planId），用于校内课案库一键复制
export async function duplicateLessonPlanFormAction(
  formData: FormData,
): Promise<void> {
  const planId = String(formData.get("planId") ?? "");
  if (!planId) return;
  const result = await duplicateLessonPlanAction(planId);
  if (result.success && result.data) {
    revalidatePath("/teacher/lesson-plans");
    redirect(`/teacher/lesson-plans/${result.data.newPlanId}/edit`);
  }
}

// ---- 模板列表 ----
export async function getLessonPlanTemplatesAction(): Promise<
  ActionState<{
    templates: Awaited<ReturnType<typeof getLessonPlanTemplates>>;
  }>
> {
  try {
    const ctx = await requirePermission(Permissions.LESSON_PLAN_READ);
    const templates = await getLessonPlanTemplates(ctx.userId);
    return { success: true, data: { templates } };
  } catch (e) {
    return handleActionError(e);
  }
}

// ---- 另存为模板 ----
export async function saveAsTemplateAction(input: {
  sourcePlanId: string;
  name: string;
}): Promise<ActionState<{ templateId: string }>> {
  const t = await getTranslations("lessonPreparation");
  try {
    const ctx = await requirePermission(Permissions.LESSON_PLAN_CREATE);
    const parsed = saveAsTemplateSchema.safeParse(input);
    if (!parsed.success) {
      const errors = await translateFieldErrors(parsed.error.flatten().fieldErrors);
      return { success: false, errors };
    }
    const { templateId } = await saveAsTemplate({
      ...parsed.data,
      userId: ctx.userId,
    });
    return { success: true, data: { templateId } };
  } catch (e) {
    if (e instanceof LessonPlanDataError && e.code === "NOT_FOUND")
      return { success: false, message: t("error.notFound") };
    return handleActionError(e);
  }
}

// ---- 删除模板 ----
export async function deleteTemplateAction(
  templateId: string,
): Promise<ActionState> {
  try {
    const ctx = await requirePermission(Permissions.LESSON_PLAN_DELETE);
    await deletePersonalTemplate(templateId, ctx.userId);
    revalidatePath("/teacher/lesson-plans");
    return { success: true };
  } catch (e) {
    return handleActionError(e);
  }
}

// ---- 获取教材列表（供 picker 使用）----
export async function getTextbooksForPickerAction(): Promise<
  ActionState<{
    textbooks: { id: string; title: string; subject: string; grade: string | null }[];
  }>
> {
  try {
    await requirePermission(Permissions.LESSON_PLAN_READ);
    const textbooks = await getTextbooksForPicker();
    return { success: true, data: { textbooks } };
  } catch (e) {
    return handleActionError(e);
  }
}

// ---- 获取章节列表（供 picker 使用）----
export async function getChaptersForPickerAction(
  textbookId: string,
): Promise<
  ActionState<{
    // P1 修复：使用 ChapterPickerOption 递归类型，替代内联的 children?: unknown[]
    chapters: import("./providers/lesson-plan-provider").ChapterPickerOption[];
  }>
> {
  try {
    await requirePermission(Permissions.LESSON_PLAN_READ);
    const chapters = await getChaptersForPicker(textbookId);
    return { success: true, data: { chapters } };
  } catch (e) {
    return handleActionError(e);
  }
}
