/**
 * M9 日历视图 - Server Actions
 */
"use server";

import { z } from "zod";
import { getCalendarEvents, groupEventsByDate } from "./data-access-calendar";
import type { LessonPlanCalendarEvent } from "./data-access-calendar";
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 getCalendarEventsSchema = z.object({
  startDate: z.string().refine((v) => !Number.isNaN(new Date(v).getTime()), "Invalid date"),
  endDate: z.string().refine((v) => !Number.isNaN(new Date(v).getTime()), "Invalid date"),
});

/**
 * 查询当前教师的备课日历事件
 */
export async function getCalendarEventsAction(
  input: Record<string, unknown>,
): Promise<ActionState<{ events: LessonPlanCalendarEvent[]; grouped: Record<string, LessonPlanCalendarEvent[]> }>> {
  try {
    await requirePermission(Permissions.LESSON_PLAN_READ);
    const parseResult = getCalendarEventsSchema.safeParse(input);
    if (!parseResult.success) {
      return { success: false, message: "Invalid input" };
    }
    const auth = await getAuthContext();
    if (!auth.userId) {
      return { success: false, message: "Unauthorized" };
    }
    const events = await getCalendarEvents(
      auth.userId,
      new Date(parseResult.data.startDate),
      new Date(parseResult.data.endDate),
    );
    const groupedMap = groupEventsByDate(events);
    const grouped: Record<string, LessonPlanCalendarEvent[]> = {};
    for (const [key, value] of groupedMap.entries()) {
      grouped[key] = value;
    }
    return { success: true, data: { events, grouped } };
  } catch (e) {
    return handleActionError(e);
  }
}
