import { and, asc, eq } from "drizzle-orm";
import { getDb } from "@/core/db/client";
import { publications } from "@/core/db/schema";
import type { TenantContext } from "@/core/tenant/types";

export async function listPublishedPublications(ctx: TenantContext) {
  const db = getDb();
  return db
    .select()
    .from(publications)
    .where(
      and(
        eq(publications.tenantId, ctx.tenantId),
        eq(publications.isPublished, true),
      ),
    )
    .orderBy(asc(publications.sortOrder));
}

export async function listDashboardPublications(ctx: TenantContext) {
  const db = getDb();
  return db
    .select()
    .from(publications)
    .where(eq(publications.tenantId, ctx.tenantId))
    .orderBy(asc(publications.sortOrder));
}

export async function createPublication(
  ctx: TenantContext,
  input: {
    title: string;
    publisher?: string;
    year?: number | null;
    url?: string;
    kind?: string;
    description?: string;
    sortOrder?: number;
    isPublished?: boolean;
  },
) {
  const db = getDb();
  const [row] = await db
    .insert(publications)
    .values({
      tenantId: ctx.tenantId,
      title: input.title.trim(),
      publisher: input.publisher?.trim() || null,
      year: input.year ?? null,
      url: input.url?.trim() || null,
      kind: input.kind?.trim() || null,
      description: input.description?.trim() || null,
      sortOrder: input.sortOrder ?? 0,
      isPublished: input.isPublished ?? true,
    })
    .returning();
  return row;
}

export async function deletePublication(ctx: TenantContext, id: string) {
  const db = getDb();
  await db
    .delete(publications)
    .where(
      and(eq(publications.id, id), eq(publications.tenantId, ctx.tenantId)),
    );
}
