import { afterAll, describe, expect, it } from "vitest";
import { getDb, getSql } from "@slackwsh/data";
import { enqueueInTx, stopBoss } from "./jobs";

const hasDatabase = Boolean(process.env.DATABASE_URL);

afterAll(async () => {
  if (!hasDatabase) return;
  await stopBoss();
  await getSql().end({ timeout: 1 });
});

describe.skipIf(!hasDatabase)("enqueueInTx", () => {
  it("inserts a pg-boss job on the drizzle postgres.js transaction", async () => {
    const db = getDb();
    let jobId: string | null = null;
    await expect(
      db.transaction(async (tx) => {
        jobId = await enqueueInTx(tx, "notifications", {
          messageId: 1,
          workspaceId: 1,
          channelId: 1,
          authorId: 1,
        });
        throw new Error("rollback-probe");
      }),
    ).rejects.toThrow("rollback-probe");
    expect(jobId).toMatch(/^[0-9a-f-]{36}$/i);
  });
});
