import { describe, it, expect, beforeEach } from 'vitest';
import type Database from 'better-sqlite3';
import { createDb } from '../src/lib/db';
import {
  createUser, countAdmins, getUserById, updateUserRole,
  updateUserPassword, deleteUser, randomPassword, isRole, hashPassword, verifyPassword,
} from '../src/lib/auth';

let db: Database.Database;
beforeEach(() => { db = createDb(':memory:'); });

describe('gestione utenti', () => {
  it('countAdmins conta i soli admin', () => {
    createUser(db, 'a1', 'segreta123', 'admin');
    createUser(db, 's1', 'segreta123', 'superuser');
    expect(countAdmins(db)).toBe(1);
  });

  it('updateUserRole e getUserById', () => {
    const id = createUser(db, 'u1', 'segreta123', 'user');
    updateUserRole(db, id, 'superuser');
    expect(getUserById(db, id)!.role).toBe('superuser');
  });

  it('updateUserPassword cambia l’hash', () => {
    const id = createUser(db, 'u2', 'vecchia123', 'user');
    updateUserPassword(db, id, hashPassword('nuova12345'));
    const hash = (db.prepare('SELECT password_hash AS h FROM users WHERE id = ?').get(id) as { h: string }).h;
    expect(verifyPassword('nuova12345', hash)).toBe(true);
  });

  it('deleteUser rimuove', () => {
    const id = createUser(db, 'u3', 'segreta123', 'user');
    deleteUser(db, id);
    expect(getUserById(db, id)).toBeNull();
  });

  it('randomPassword genera almeno 12 caratteri', () => {
    expect(randomPassword().length).toBeGreaterThanOrEqual(12);
  });

  it('isRole valida i ruoli', () => {
    expect(isRole('admin')).toBe(true);
    expect(isRole('superuser')).toBe(true);
    expect(isRole('user')).toBe(true);
    expect(isRole('editor')).toBe(false);
    expect(isRole(3)).toBe(false);
  });
});
