// src/lib/billing/authorize.test.ts — integration test on isOrgBillingManager.
// Gated on DB_TESTS=1, run against the *_test DB only.
import { afterAll, beforeAll, describe, expect, mock, test } from "bun:test";

mock.module("server-only", () => ({}));

const RUN_DB = process.env.DB_TESTS === "1";

describe.skipIf(!RUN_DB)("isOrgBillingManager (postgres)", () => {
  let db: typeof import("@/lib/db/client").db;
  let schema: typeof import("@/lib/db/auth-schema");
  let mod: typeof import("./authorize");

  const ORG = "test-authz-org";
  const OWNER = "test-authz-owner";
  const ADMIN = "test-authz-admin";
  const STAFF = "test-authz-staff";
  const OUTSIDER = "test-authz-outsider";
  const USERS = [OWNER, ADMIN, STAFF, OUTSIDER];

  async function cleanup() {
    const { eq, inArray } = await import("drizzle-orm");
    await db.delete(schema.member).where(eq(schema.member.organizationId, ORG));
    await db.delete(schema.organization).where(eq(schema.organization.id, ORG));
    await db.delete(schema.user).where(inArray(schema.user.id, USERS));
  }

  beforeAll(async () => {
    ({ db } = await import("@/lib/db/client"));
    schema = await import("@/lib/db/auth-schema");
    mod = await import("./authorize");
    const { assertTestDb } = await import("@/lib/db/assert-test-db");
    await assertTestDb();
    await cleanup();
    const now = new Date();
    await db.insert(schema.user).values(
      USERS.map((id) => ({
        id,
        name: id,
        email: `${id}@test.dev`,
        emailVerified: true,
        createdAt: now,
        updatedAt: now,
      })),
    );
    await db.insert(schema.organization).values({
      id: ORG,
      name: "Test Authz Org",
      slug: `test-authz-org-${crypto.randomUUID().slice(0, 8)}`,
      createdAt: now,
    });
    await db.insert(schema.member).values([
      {
        id: crypto.randomUUID(),
        organizationId: ORG,
        userId: OWNER,
        role: "owner",
        createdAt: now,
      },
      {
        id: crypto.randomUUID(),
        organizationId: ORG,
        userId: ADMIN,
        role: "admin",
        createdAt: now,
      },
      {
        id: crypto.randomUUID(),
        organizationId: ORG,
        userId: STAFF,
        role: "member",
        createdAt: now,
      },
    ]);
  });

  afterAll(async () => {
    await cleanup();
  });

  test("owner can manage billing", async () => {
    expect(await mod.isOrgBillingManager(OWNER, ORG)).toBe(true);
  });

  test("admin cannot manage billing", async () => {
    expect(await mod.isOrgBillingManager(ADMIN, ORG)).toBe(false);
  });

  test("member cannot manage billing", async () => {
    expect(await mod.isOrgBillingManager(STAFF, ORG)).toBe(false);
  });

  test("non-member cannot manage billing", async () => {
    expect(await mod.isOrgBillingManager(OUTSIDER, ORG)).toBe(false);
  });
});
