import "./setup-env.js";
import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { createDatabase, schema } from "@app/database";
import { processSafetyCanary } from "../src/processors/safety-canary.js";
import type { WorkerContext } from "../src/context.js";

const testDb = createDatabase(process.env.TEST_DATABASE_URL!);
const ctx: WorkerContext = { db: testDb.db } as never;

describe("RUN_SAFETY_CANARY", () => {
  beforeAll(async () => {
    await testDb.db.delete(schema.opsSafetyCanary);
  });

  afterAll(async () => {
    await testDb.db.delete(schema.opsSafetyCanary);
    await testDb.pool.end();
  });

  it("re-härleder allergener och skriver en canary-rad", async () => {
    const result = await processSafetyCanary(ctx);

    expect(typeof result.allergenInvariantBrott).toBe("number");
    expect(typeof result.overifieradeVisade).toBe("number");
    expect(result.allergenInvariantBrott).toBeGreaterThanOrEqual(0);

    const latest = await testDb.db
      .select()
      .from(schema.opsSafetyCanary)
      .orderBy(schema.opsSafetyCanary.occurredAt)
      .limit(1);
    expect(latest.length).toBe(1);
    expect(latest[0]!.allergenInvariantBrott).toBe(result.allergenInvariantBrott);
  });
});
