import "server-only";

import { like } from "drizzle-orm";

import { db } from "@/shared/db";
import { lessonPlans } from "@/shared/db/schema";
import { normalizeDocument } from "./data-access";
import type { LessonPlanListItem } from "./types";

// 查询关联了某知识点的课案
export async function getLessonPlansByKnowledgePoint(
  knowledgePointId: string,
): Promise<LessonPlanListItem[]> {
  // content 是 JSON，用 LIKE 粗筛后内存精确过滤
  const rows = await db
    .select()
    .from(lessonPlans)
    .where(like(lessonPlans.content, `%${knowledgePointId}%`));
  // 类型守卫：过滤出包含该知识点的课案，并映射为 LessonPlanListItem
  return rows
    .filter((r) => {
      const doc = normalizeDocument(r.content);
      return doc.nodes.some((b) => {
        const data = b.data as { knowledgePointIds?: string[] };
        return data?.knowledgePointIds?.includes(knowledgePointId);
      });
    })
    .map((r) => ({
      id: r.id,
      title: r.title,
      textbookId: r.textbookId,
      chapterId: r.chapterId,
      coursePlanItemId: r.coursePlanItemId,
      subjectId: r.subjectId,
      gradeId: r.gradeId,
      templateId: r.templateId,
      templateName: r.templateName,
      content: normalizeDocument(r.content),
      status: r.status as LessonPlanListItem["status"],
      creatorId: r.creatorId,
      lastSavedAt: r.lastSavedAt?.toISOString() ?? null,
      createdAt: r.createdAt.toISOString(),
      updatedAt: r.updatedAt.toISOString(),
      textbookTitle: null,
      chapterTitle: null,
      subjectName: null,
      gradeName: null,
      creatorName: null,
    }));
}

// 查询使用了某题目的课案
export async function getLessonPlansByQuestion(
  questionId: string,
): Promise<LessonPlanListItem[]> {
  const rows = await db
    .select()
    .from(lessonPlans)
    .where(like(lessonPlans.content, `%${questionId}%`));
  return rows
    .filter((r) => {
      const doc = normalizeDocument(r.content);
      return doc.nodes.some((b) => {
        if (b.type !== "exercise") return false;
        const data = b.data as { items?: Array<{ questionId: string }> };
        return data?.items?.some((it) => it.questionId === questionId);
      });
    })
    .map((r) => ({
      id: r.id,
      title: r.title,
      textbookId: r.textbookId,
      chapterId: r.chapterId,
      coursePlanItemId: r.coursePlanItemId,
      subjectId: r.subjectId,
      gradeId: r.gradeId,
      templateId: r.templateId,
      templateName: r.templateName,
      content: normalizeDocument(r.content),
      status: r.status as LessonPlanListItem["status"],
      creatorId: r.creatorId,
      lastSavedAt: r.lastSavedAt?.toISOString() ?? null,
      createdAt: r.createdAt.toISOString(),
      updatedAt: r.updatedAt.toISOString(),
      textbookTitle: null,
      chapterTitle: null,
      subjectName: null,
      gradeName: null,
      creatorName: null,
    }));
}
