/**
 * M6 资源附件库 - Server Actions
 */
"use server";

import { getTranslations } from "next-intl/server";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import {
  getAttachmentsByPlanId,
  getAttachmentsByBlockId,
  createAttachment,
  deleteAttachment,
  updateAttachmentType,
  getAttachmentById,
} from "./data-access-attachments";
import type { ActionState } from "@/shared/types/action-state";
import { getAuthContext, requirePermission } from "@/shared/lib/auth-guard";
import { handleActionError } from "@/shared/lib/action-utils";
import { Permissions } from "@/shared/types/permissions";

const createAttachmentSchema = z.object({
  planId: z.string().min(1, "error.planIdRequired"),
  blockId: z.string().optional(),
  fileId: z.string().min(1, "error.fileIdRequired"),
  displayName: z.string().min(1, "error.displayNameRequired").max(255, "error.displayNameTooLong"),
  attachmentType: z.enum(["reference", "material", "supplementary"]).default("reference"),
});

const updateAttachmentTypeSchema = z.object({
  attachmentId: z.string().min(1, "error.attachmentIdRequired"),
  attachmentType: z.enum(["reference", "material", "supplementary"]),
});

/**
 * 查询课案附件列表
 */
export async function getLessonPlanAttachmentsAction(
  planId: string,
  blockId?: string,
): Promise<
  ActionState<{ items: Awaited<ReturnType<typeof getAttachmentsByPlanId>> }>
> {
  try {
    await requirePermission(Permissions.LESSON_PLAN_READ);
    const items = blockId
      ? await getAttachmentsByBlockId(planId, blockId)
      : await getAttachmentsByPlanId(planId);
    return { success: true, data: { items } };
  } catch (e) {
    return handleActionError(e);
  }
}

/**
 * 添加附件
 */
export async function createLessonPlanAttachmentAction(
  input: Record<string, unknown>,
): Promise<
  ActionState<{ attachment: Awaited<ReturnType<typeof getAttachmentById>> }>
> {
  try {
    await requirePermission(Permissions.LESSON_PLAN_UPDATE);
    const t = await getTranslations("lessonPreparation");
    const parseResult = createAttachmentSchema.safeParse(input);
    if (!parseResult.success) {
      return {
        success: false,
        message: t("error.invalidInput"),
        errors: Object.fromEntries(
          Object.entries(parseResult.error.flatten().fieldErrors),
        ),
      };
    }

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

/**
 * 删除附件
 */
export async function deleteLessonPlanAttachmentAction(
  attachmentId: string,
): Promise<ActionState<null>> {
  try {
    await requirePermission(Permissions.LESSON_PLAN_UPDATE);
    await deleteAttachment(attachmentId);
    return { success: true, data: null };
  } catch (e) {
    return handleActionError(e);
  }
}

/**
 * 更新附件类型
 */
export async function updateAttachmentTypeAction(
  input: Record<string, unknown>,
): Promise<ActionState<null>> {
  try {
    await requirePermission(Permissions.LESSON_PLAN_UPDATE);
    const parseResult = updateAttachmentTypeSchema.safeParse(input);
    if (!parseResult.success) {
      return { success: false, message: "Invalid input" };
    }
    await updateAttachmentType(
      parseResult.data.attachmentId,
      parseResult.data.attachmentType,
    );
    return { success: true, data: null };
  } catch (e) {
    return handleActionError(e);
  }
}
