"use server";

import { revalidatePath } from "next/cache";
import { getTranslations } from "next-intl/server";
import {
  requirePermission,
  PermissionDeniedError,
} from "@/shared/lib/auth-guard";
import { Permissions } from "@/shared/types/permissions";
import { publishLessonPlanHomework, PublishServiceError } from "./publish-service";
import type { ActionState } from "./types";

export async function publishLessonPlanHomeworkAction(input: {
  planId: string;
  blockId: string;
  classIds: string[];
  availableAt?: string;
  dueAt?: string;
}): Promise<ActionState<{ examId: string; assignmentId: string }>> {
  const t = await getTranslations("lessonPreparation");
  try {
    const ctx = await requirePermission(
      Permissions.LESSON_PLAN_PUBLISH,
    );
    await requirePermission(Permissions.HOMEWORK_CREATE);
    const result = await publishLessonPlanHomework({
      planId: input.planId,
      blockId: input.blockId,
      userId: ctx.userId,
      classIds: input.classIds,
      availableAt: input.availableAt
        ? new Date(input.availableAt)
        : undefined,
      dueAt: input.dueAt ? new Date(input.dueAt) : undefined,
    });
    revalidatePath("/teacher/lesson-plans");
    revalidatePath("/teacher/homework");
    return {
      success: true,
      data: {
        examId: result.examId,
        assignmentId: result.assignmentId,
      },
    };
  } catch (e) {
    if (e instanceof PermissionDeniedError)
      return { success: false, message: e.message };
    // publish-service 抛出 PublishServiceError（含 code），翻译为 i18n 消息
    if (e instanceof PublishServiceError) {
      const messageKey = PUBLISH_ERROR_KEY_MAP[e.code] ?? "error.publish";
      return { success: false, message: t(messageKey) };
    }
    return {
      success: false,
      message: e instanceof Error ? e.message : t("error.publish"),
    };
  }
}

// publish-service 错误码 → i18n 键映射
const PUBLISH_ERROR_KEY_MAP: Record<string, string> = {
  PLAN_NOT_FOUND: "publish.planNotFound",
  NO_PERMISSION: "publish.noPermission",
  NO_EXERCISE_BLOCK: "publish.noExerciseBlock",
  NO_QUESTIONS: "publish.noQuestions",
  ALREADY_PUBLISHED: "publish.alreadyPublished",
  NO_SUBJECT_OR_GRADE: "publish.noSubjectOrGrade",
  NO_STUDENTS: "publish.noStudents",
};
