import { describe, it, expect, beforeAll } from 'vitest';
import { createPgliteClient } from '@platform-modules/db/pglite';
import { createCustomEngine, customAuthSchema } from '@platform-modules/auth/engine-custom';
import authSchemaSql from '../db/auth-schema.sql?raw';
import { assertNotLastAdmin, LastAdminError } from './user-admin.js';

const SECRET = 'user-admin-test-secret';
const PEPPER = { currentVersion: 'v1' as const, secrets: { v1: 'test-pepper' } };

describe('assertNotLastAdmin', () => {
  let engine: ReturnType<typeof createCustomEngine>;

  beforeAll(async () => {
    const db = createPgliteClient({ schema: customAuthSchema });
    for (const stmt of authSchemaSql.split(';').map((s) => s.trim()).filter(Boolean)) {
      await db.execute(stmt);
    }
    engine = createCustomEngine({ db, jwtSecrets: [SECRET], pepper: PEPPER });
    await engine.createUser({ email: 'only-admin@x.test', password: 'pw-only-admin', roles: ['admin'] });
  });

  it('refuses demoting the only active admin', async () => {
    const { users } = await engine.listUsers({ limit: 10 });
    const admin = users.find((u) => u.email === 'only-admin@x.test');
    expect(admin).toBeTruthy();
    await expect(assertNotLastAdmin(engine, admin!.id, ['editor'])).rejects.toBeInstanceOf(LastAdminError);
  });

  it('refuses disabling the only active admin', async () => {
    const { users } = await engine.listUsers({ limit: 10 });
    const admin = users.find((u) => u.email === 'only-admin@x.test');
    await expect(assertNotLastAdmin(engine, admin!.id)).rejects.toBeInstanceOf(LastAdminError);
  });
});
