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

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

describe('ruoli', () => {
  it('createUser accetta i tre ruoli e getSessionUser li ritorna', () => {
    createUser(db, 'u', 'segreta123', 'user');
    createUser(db, 's', 'segreta123', 'superuser');
    expect(getSessionUser(db, login(db, 'u', 'segreta123')!)).toMatchObject({ role: 'user' });
    expect(getSessionUser(db, login(db, 's', 'segreta123')!)).toMatchObject({ role: 'superuser' });
  });

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

describe('canAccessAdminPath', () => {
  it('admin accede a tutto', () => {
    for (const p of ['/admin', '/admin/users', '/admin/content', '/api/admin/posts', '/api/admin/users/1'])
      expect(canAccessAdminPath('admin', p)).toBe(true);
  });

  it('superuser: contenuti + blog sì, utenti no', () => {
    expect(canAccessAdminPath('superuser', '/admin/content')).toBe(true);
    expect(canAccessAdminPath('superuser', '/admin/content/')).toBe(true);
    expect(canAccessAdminPath('superuser', '/api/admin/content/home.hero.title')).toBe(true);
    expect(canAccessAdminPath('superuser', '/admin')).toBe(true);
    expect(canAccessAdminPath('superuser', '/admin/new')).toBe(true);
    expect(canAccessAdminPath('superuser', '/api/admin/posts')).toBe(true);
    expect(canAccessAdminPath('superuser', '/admin/users')).toBe(false);
    expect(canAccessAdminPath('superuser', '/api/admin/users/1')).toBe(false);
  });

  it('user: blog sì, contenuti e utenti no', () => {
    expect(canAccessAdminPath('user', '/admin')).toBe(true);
    expect(canAccessAdminPath('user', '/admin/new')).toBe(true);
    expect(canAccessAdminPath('user', '/api/admin/posts')).toBe(true);
    expect(canAccessAdminPath('user', '/api/admin/upload')).toBe(true);
    expect(canAccessAdminPath('user', '/admin/logout')).toBe(true);
    expect(canAccessAdminPath('user', '/admin/content')).toBe(false);
    expect(canAccessAdminPath('user', '/api/admin/content/x')).toBe(false);
    expect(canAccessAdminPath('user', '/admin/users')).toBe(false);
  });

  it('la matrice non confonde prefissi simili', () => {
    expect(canAccessAdminPath('user', '/admin/contentious')).toBe(true); // NON è /admin/content
    expect(canAccessAdminPath('superuser', '/admin/users-x')).toBe(true); // NON è /admin/users
  });
});

describe('landingFor', () => {
  it('instrada ogni ruolo alla sua home', () => {
    expect(landingFor('superuser')).toBe('/admin/content');
    expect(landingFor('user')).toBe('/admin');
    expect(landingFor('admin')).toBe('/admin');
  });
});
