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

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

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

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

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