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

/**
 * A post is publicly visible when:
 *  - status = "published", AND
 *  - scheduledAt is null OR scheduledAt <= now()
 * Admins see everything.
 */
function publicVisibilityFilter() {
  return and(
    eq(blogPosts.status, "published"),
    or(isNull(blogPosts.scheduledAt), lte(blogPosts.scheduledAt, sql`now()`)),
  );
}

export async function listPublishedBlogPosts() {
  return db
    .select()
    .from(blogPosts)
    .where(publicVisibilityFilter())
    .orderBy(desc(blogPosts.publishedAt));
}

export async function getPublishedBlogPostBySlug(slug: string) {
  const [row] = await db
    .select()
    .from(blogPosts)
    .where(and(eq(blogPosts.slug, slug), publicVisibilityFilter()))
    .limit(1);
  return row ?? null;
}

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

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