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

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

describe('ruoli', () => {
  it('createUser accetta ruolo editor e getSessionUser lo ritorna', () => {
    createUser(db, 'cliente', 'segreta123', 'editor');
    const token = login(db, 'cliente', 'segreta123')!;
    expect(getSessionUser(db, token)).toMatchObject({ username: 'cliente', role: 'editor' });
  });

  it('createUser senza ruolo crea admin', () => {
    createUser(db, 'adriano', 'segreta123');
    const token = login(db, 'adriano', 'segreta123')!;
    expect(getSessionUser(db, token)).toMatchObject({ role: 'admin' });
  });

  it('admin accede a tutto, editor solo a contenuti e logout', () => {
    expect(canAccessAdminPath('admin', '/admin')).toBe(true);
    expect(canAccessAdminPath('admin', '/api/admin/posts')).toBe(true);
    expect(canAccessAdminPath('editor', '/admin/content')).toBe(true);
    expect(canAccessAdminPath('editor', '/api/admin/content/home.hero.title')).toBe(true);
    expect(canAccessAdminPath('editor', '/admin/logout')).toBe(true);
    expect(canAccessAdminPath('editor', '/admin')).toBe(false);
    expect(canAccessAdminPath('editor', '/admin/new')).toBe(false);
    expect(canAccessAdminPath('editor', '/api/admin/posts')).toBe(false);
    expect(canAccessAdminPath('editor', '/api/admin/upload')).toBe(false);
  });
});
