/**
 * M10 备课分析仪表盘 - Server Actions
 */
"use server";

import { z } from "zod";
import {
  getTeacherInvestment,
  getTemplateUsageStats,
  getStandardsCoverageHeatmap,
  getGlobalLessonPlanStats,
} from "./data-access-analytics";
import type {
  TeacherInvestmentDataPoint,
  TemplateUsageDataPoint,
  StandardsCoverageCell,
} from "./data-access-analytics";
import type { ActionState } from "@/shared/types/action-state";
import { requirePermission } from "@/shared/lib/auth-guard";
import { handleActionError } from "@/shared/lib/action-utils";

const dateSchema = z.string().refine((v) => !Number.isNaN(new Date(v).getTime()), "Invalid date");

const queryInvestmentSchema = z.object({
  startDate: dateSchema,
  endDate: dateSchema,
  teacherId: z.string().optional(),
});

/**
 * 查询教师备课投入
 */
export async function getTeacherInvestmentAction(
  input: Record<string, unknown>,
): Promise<ActionState<{ items: TeacherInvestmentDataPoint[] }>> {
  try {
    // M10 备课分析仪表盘需要管理员权限
    await requirePermission("lesson_plan:read");
    const parseResult = queryInvestmentSchema.safeParse(input);
    if (!parseResult.success) {
      return { success: false, message: "Invalid input" };
    }
    const items = await getTeacherInvestment(
      new Date(parseResult.data.startDate),
      new Date(parseResult.data.endDate),
      parseResult.data.teacherId,
    );
    return { success: true, data: { items } };
  } catch (e) {
    return handleActionError(e);
  }
}

/**
 * 查询模板使用率
 */
export async function getTemplateUsageStatsAction(): Promise<
  ActionState<{ items: TemplateUsageDataPoint[] }>
> {
  try {
    await requirePermission("lesson_plan:read");
    const items = await getTemplateUsageStats();
    return { success: true, data: { items } };
  } catch (e) {
    return handleActionError(e);
  }
}

/**
 * 查询课标覆盖热力图
 */
export async function getStandardsCoverageHeatmapAction(): Promise<
  ActionState<{ items: StandardsCoverageCell[] }>
> {
  try {
    await requirePermission("lesson_plan:read");
    const items = await getStandardsCoverageHeatmap();
    return { success: true, data: { items } };
  } catch (e) {
    return handleActionError(e);
  }
}

/**
 * 查询全局备课统计
 */
export async function getGlobalLessonPlanStatsAction(): Promise<
  ActionState<{ stats: Awaited<ReturnType<typeof getGlobalLessonPlanStats>> }>
> {
  try {
    await requirePermission("lesson_plan:read");
    const stats = await getGlobalLessonPlanStats();
    return { success: true, data: { stats } };
  } catch (e) {
    return handleActionError(e);
  }
}
