import { drizzle, type NodePgDatabase } from "drizzle-orm/node-postgres";
import { eq } from "drizzle-orm";
import pg from "pg";
import { ingestionCursor } from "@sidetrail/db";

const { Pool } = pg;

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
});

export const db: NodePgDatabase = drizzle(pool);

export async function getCursor(): Promise<number | undefined> {
  const result = await db.select().from(ingestionCursor).where(eq(ingestionCursor.id, 1));
  const cursor = result[0]?.cursorUs;
  return cursor && cursor !== 0 ? cursor : undefined;
}

export async function setCursor(cursorUs: number): Promise<void> {
  await db
    .update(ingestionCursor)
    .set({ cursorUs, updatedAt: new Date() })
    .where(eq(ingestionCursor.id, 1));
}
