/**
 * M3 审核工作流 - Server Actions
 */
"use server";

import { getTranslations } from "next-intl/server";
import { revalidatePath } from "next/cache";
import {
  submitLessonPlanForReviewSchema,
  reviewLessonPlanSchema,
} from "./schema";
import {
  submitForReview,
  reviewPlan,
  getReviewRecordsByPlanId,
  getPendingReviewPlans,
  withdrawSubmission,
} from "./data-access-review";
import type { LessonPlanReviewRecord } from "./data-access-review";
import type { ActionState } from "@/shared/types/action-state";
import { getAuthContext, requirePermission } from "@/shared/lib/auth-guard";
import { handleActionError } from "@/shared/lib/action-utils";
import { safeParseWithI18n } from "./lib/i18n-errors";
import { Permissions } from "@/shared/types/permissions";

/**
 * 教师提交课案审核
 */
export async function submitLessonPlanForReviewAction(
  input: Record<string, unknown>,
): Promise<ActionState<{ status: string }>> {
  try {
    await requirePermission(Permissions.LESSON_PLAN_UPDATE);
    const t = await getTranslations("lessonPreparation");
    const parseResult = await safeParseWithI18n(submitLessonPlanForReviewSchema, input);
    if (!parseResult.success) return parseResult;

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

/**
 * 教研组长审核课案
 */
export async function reviewLessonPlanAction(
  input: Record<string, unknown>,
): Promise<ActionState<{ newStatus: string; record: LessonPlanReviewRecord }>> {
  try {
    await requirePermission(Permissions.LESSON_PLAN_PUBLISH); // 暂复用 publish 权限
    const t = await getTranslations("lessonPreparation");
    const parseResult = await safeParseWithI18n(reviewLessonPlanSchema, input);
    if (!parseResult.success) return parseResult;

    const auth = await getAuthContext();
    if (!auth.userId) {
      return { success: false, message: t("error.unauthorized") };
    }

    const { newStatus, record } = await reviewPlan(
      parseResult.data.planId,
      auth.userId,
      parseResult.data.decision,
      parseResult.data.reviewComment,
    );
    revalidatePath(`/teacher/lesson-plans/${parseResult.data.planId}/edit`);
    return { success: true, data: { newStatus, record } };
  } catch (e) {
    return handleActionError(e);
  }
}

/**
 * 查询课案审核记录
 */
export async function getLessonPlanReviewRecordsAction(
  planId: string,
): Promise<ActionState<{ records: LessonPlanReviewRecord[] }>> {
  try {
    await requirePermission(Permissions.LESSON_PLAN_READ);
    const records = await getReviewRecordsByPlanId(planId);
    return { success: true, data: { records } };
  } catch (e) {
    return handleActionError(e);
  }
}

/**
 * 查询待审核队列
 */
export async function getPendingReviewPlansAction(): Promise<
  ActionState<{ items: Awaited<ReturnType<typeof getPendingReviewPlans>> }>
> {
  try {
    await requirePermission(Permissions.LESSON_PLAN_PUBLISH);
    const auth = await getAuthContext();
    if (!auth.userId) {
      return { success: false, message: "Unauthorized" };
    }
    const items = await getPendingReviewPlans();
    return { success: true, data: { items } };
  } catch (e) {
    return handleActionError(e);
  }
}

/**
 * 撤回提交
 */
export async function withdrawSubmissionAction(
  planId: string,
): Promise<ActionState<{ status: string }>> {
  try {
    await requirePermission(Permissions.LESSON_PLAN_UPDATE);
    const status = await withdrawSubmission(planId);
    revalidatePath(`/teacher/lesson-plans/${planId}/edit`);
    return { success: true, data: { status } };
  } catch (e) {
    return handleActionError(e);
  }
}
