/**
 * V5-7：课案-课时绑定 Server Actions
 */
"use server";

import { getTranslations } from "next-intl/server";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import {
  getSchedulesByPlanId,
  createSchedule,
  deleteSchedule,
} from "./data-access-schedules";
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 createScheduleSchema = z.object({
  planId: z.string().min(1, "error.planIdRequired"),
  classId: z.string().min(1, "error.classIdRequired"),
  scheduledDate: z.string().min(1, "error.dateRequired"),
  period: z.number().int().min(1).max(12),
  classScheduleId: z.string().optional(),
  durationMin: z.number().int().min(5).max(180).optional(),
});

export async function getLessonPlanSchedulesAction(
  planId: string,
): Promise<ActionState<{ items: Awaited<ReturnType<typeof getSchedulesByPlanId>> }>> {
  try {
    await requirePermission(Permissions.LESSON_PLAN_READ);
    const items = await getSchedulesByPlanId(planId);
    return { success: true, data: { items } };
  } catch (e) {
    return handleActionError(e);
  }
}

export async function createLessonPlanScheduleAction(
  input: Record<string, unknown>,
): Promise<ActionState<{ schedule: Awaited<ReturnType<typeof createSchedule>> }>> {
  try {
    await requirePermission(Permissions.LESSON_PLAN_UPDATE);
    const t = await getTranslations("lessonPreparation");
    const parseResult = createScheduleSchema.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") };
    }

    const schedule = await createSchedule({
      ...parseResult.data,
      createdBy: auth.userId,
    });

    revalidatePath("/teacher/lesson-plans");
    revalidatePath("/teacher/lesson-plans/calendar");
    return { success: true, data: { schedule } };
  } catch (e) {
    return handleActionError(e);
  }
}

export async function deleteLessonPlanScheduleAction(
  scheduleId: string,
): Promise<ActionState<null>> {
  try {
    await requirePermission(Permissions.LESSON_PLAN_UPDATE);
    await deleteSchedule(scheduleId);
    revalidatePath("/teacher/lesson-plans");
    revalidatePath("/teacher/lesson-plans/calendar");
    return { success: true, data: null };
  } catch (e) {
    return handleActionError(e);
  }
}
