import "server-only";
import { and, desc, eq, lte, gte, or, isNull } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { notifications } from "@/lib/db/schema";

export async function listActiveNotifications() {
  const now = new Date();
  return db
    .select()
    .from(notifications)
    .where(
      and(
        eq(notifications.active, true),
        or(isNull(notifications.startsAt), lte(notifications.startsAt, now)),
        or(isNull(notifications.endsAt), gte(notifications.endsAt, now)),
      ),
    )
    .orderBy(desc(notifications.createdAt));
}

export async function listNotificationsForAdmin() {
  return db.select().from(notifications).orderBy(desc(notifications.createdAt));
}

export async function getNotificationForAdmin(id: string) {
  const [row] = await db
    .select()
    .from(notifications)
    .where(eq(notifications.id, id))
    .limit(1);
  return row ?? null;
}
