import "server-only";
import { prisma } from "@/lib/db";
import type { Role } from "@prisma/client";

/**
 * Announcement reads.
 *
 * Visibility is expressed in SQL so an out-of-scope row can never be
 * serialised into the RSC payload:
 *   • ADMIN   — every announcement.
 *   • TEACHER — announcements they authored, school-wide posts, and posts
 *               targeted at a class they teach or a course they own.
 *   • STUDENT — school-wide posts, plus posts targeted at a class they are
 *               enrolled in or a course they are enrolled in.
 */

export interface AnnouncementScope {
  userId: string;
  role: Role;
}

export interface AnnouncementRow {
  id: string;
  title: string;
  body: string;
  pinned: boolean;
  publishedAt: Date;
  author: { id: string; fullName: string; avatarUrl: string | null };
  /** Raw target ids, used to prefill the edit dialog. */
  classId: string | null;
  courseId: string | null;
  /** Classroom name when the post targets a class. */
  classroomName: string | null;
  /** Course title when the post targets a course. */
  courseTitle: string | null;
  /** True when the signed-in actor may edit or delete this row. */
  canManage: boolean;
}

export interface AnnouncementFilters {
  search?: string;
}

/** Prisma `where` fragment expressing which announcements the actor may read. */
function announcementAccessFilter(scope: AnnouncementScope) {
  if (scope.role === "ADMIN") return {};

  if (scope.role === "TEACHER") {
    return {
      OR: [
        { authorId: scope.userId },
        { classId: null, courseId: null },
        { classroom: { teacherId: scope.userId } },
        { course: { teacherId: scope.userId } },
        { course: { classroom: { teacherId: scope.userId } } },
      ],
    };
  }

  return {
    OR: [
      { classId: null, courseId: null },
      { classroom: { enrollments: { some: { studentId: scope.userId, status: "ACTIVE" as const } } } },
      { course: { enrollments: { some: { studentId: scope.userId, status: "ACTIVE" as const } } } },
    ],
  };
}

export async function listAnnouncements(
  scope: AnnouncementScope,
  filters: AnnouncementFilters = {}
): Promise<AnnouncementRow[]> {
  const announcements = await prisma.announcement.findMany({
    where: {
      AND: [
        announcementAccessFilter(scope),
        filters.search
          ? {
              OR: [
                { title: { contains: filters.search, mode: "insensitive" as const } },
                { body: { contains: filters.search, mode: "insensitive" as const } },
              ],
            }
          : {},
      ],
    },
    orderBy: [{ pinned: "desc" }, { publishedAt: "desc" }],
    select: {
      id: true,
      title: true,
      body: true,
      pinned: true,
      publishedAt: true,
      authorId: true,
      classId: true,
      courseId: true,
      author: { select: { id: true, fullName: true, avatarUrl: true } },
      classroom: { select: { name: true } },
      course: { select: { title: true } },
    },
  });

  return announcements.map((announcement) => ({
    id: announcement.id,
    title: announcement.title,
    body: announcement.body,
    pinned: announcement.pinned,
    publishedAt: announcement.publishedAt,
    author: announcement.author,
    classId: announcement.classId,
    courseId: announcement.courseId,
    classroomName: announcement.classroom?.name ?? null,
    courseTitle: announcement.course?.title ?? null,
    canManage: scope.role === "ADMIN" || announcement.authorId === scope.userId,
  }));
}

export interface AnnouncementTargetOptions {
  classrooms: { id: string; name: string }[];
  courses: { id: string; title: string }[];
}

/**
 * Classrooms and courses the actor may address an announcement to.
 * Admins see everything; teachers see their own classes and courses.
 */
export async function listAnnouncementTargets(
  scope: AnnouncementScope
): Promise<AnnouncementTargetOptions> {
  const isAdmin = scope.role === "ADMIN";

  const [classrooms, courses] = await Promise.all([
    prisma.classroom.findMany({
      where: { archivedAt: null, ...(isAdmin ? {} : { teacherId: scope.userId }) },
      orderBy: { name: "asc" },
      select: { id: true, name: true },
    }),
    prisma.course.findMany({
      where: isAdmin ? {} : { teacherId: scope.userId },
      orderBy: { title: "asc" },
      select: { id: true, title: true },
    }),
  ]);

  return { classrooms, courses };
}
