import { describe, it, expect, beforeEach } from 'vitest';
import type Database from 'better-sqlite3';
import { createDb } from '../src/lib/db';
import { hashPassword, verifyPassword, createUser, login, getSessionUser, logout } from '../src/lib/auth';

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

describe('auth', () => {
  it('hash e verifica password', () => {
    const h = hashPassword('segreta123');
    expect(h).not.toBe('segreta123');
    expect(verifyPassword('segreta123', h)).toBe(true);
    expect(verifyPassword('sbagliata', h)).toBe(false);
  });

  it('login corretto crea sessione recuperabile', () => {
    createUser(db, 'adriano', 'segreta123');
    const token = login(db, 'adriano', 'segreta123');
    expect(token).toBeTruthy();
    const user = getSessionUser(db, token!);
    expect(user).toMatchObject({ username: 'adriano' });
  });

  it('login errato ritorna null', () => {
    createUser(db, 'adriano', 'segreta123');
    expect(login(db, 'adriano', 'sbagliata')).toBeNull();
    expect(login(db, 'inesistente', 'x')).toBeNull();
  });

  it('sessione scaduta viene rifiutata ed eliminata', () => {
    createUser(db, 'adriano', 'segreta123');
    const token = login(db, 'adriano', 'segreta123')!;
    db.prepare("UPDATE sessions SET expires_at = datetime('now', '-1 day')").run();
    expect(getSessionUser(db, token)).toBeNull();
    expect(db.prepare('SELECT COUNT(*) AS n FROM sessions').get()).toMatchObject({ n: 0 });
  });

  it('logout elimina la sessione', () => {
    createUser(db, 'adriano', 'segreta123');
    const token = login(db, 'adriano', 'segreta123')!;
    logout(db, token);
    expect(getSessionUser(db, token)).toBeNull();
  });
});
