// Wiring test for the global `admin` plugin: the Drizzle schema must carry the
// plugin's columns, the auth instance must expose its server endpoints, and the
// super-admin → role:"admin" bridge predicate must follow SUPER_ADMIN_EMAILS.
import { describe, expect, test } from "bun:test";
import { env } from "@/env";
import { auth, isSuperAdminEmail } from "../auth";
import { session, user } from "../db/auth-schema";

describe("admin plugin wiring", () => {
  test("user table carries the admin plugin columns", () => {
    // better-auth 1.6.17 admin schema → user: role, banned, banReason, banExpires.
    expect(user.role.name).toBe("role");
    expect(user.banned.name).toBe("banned");
    expect(user.banReason.name).toBe("ban_reason");
    expect(user.banExpires.name).toBe("ban_expires");
  });

  test("session table carries impersonatedBy", () => {
    expect(session.impersonatedBy.name).toBe("impersonated_by");
  });

  test("auth.api exposes the admin endpoints", () => {
    expect(typeof auth.api.listUsers).toBe("function");
    expect(typeof auth.api.banUser).toBe("function");
    expect(typeof auth.api.unbanUser).toBe("function");
    expect(typeof auth.api.setRole).toBe("function");
    expect(typeof auth.api.impersonateUser).toBe("function");
    expect(typeof auth.api.stopImpersonating).toBe("function");
  });
});

describe("super-admin → admin role bridge", () => {
  const listed = (env.SUPER_ADMIN_EMAILS ?? "")
    .split(",")
    .map((e) => e.trim())
    .filter(Boolean);

  test.skipIf(listed.length === 0)(
    "matches a configured super-admin email (case-insensitively)",
    () => {
      const sample = listed[0];
      expect(isSuperAdminEmail(sample)).toBe(true);
      expect(isSuperAdminEmail(sample.toUpperCase())).toBe(true);
      expect(isSuperAdminEmail(`  ${sample}  `)).toBe(true);
    },
  );

  test("rejects a non-super-admin email + empty/nullish input", () => {
    expect(isSuperAdminEmail("definitely-not-an-admin@example.invalid")).toBe(
      false,
    );
    expect(isSuperAdminEmail("")).toBe(false);
    expect(isSuperAdminEmail(null)).toBe(false);
    expect(isSuperAdminEmail(undefined)).toBe(false);
  });
});
