import { describe, it, expect } from 'vitest';
import { createDb } from '../src/lib/db';

describe('schema content_blocks e ruoli', () => {
  it('crea la tabella content_blocks', () => {
    const db = createDb(':memory:');
    const cols = db.prepare(`PRAGMA table_info(content_blocks)`).all() as { name: string }[];
    expect(cols.map((c) => c.name)).toEqual(
      expect.arrayContaining(['tag', 'type', 'value', 'styles', 'updated_at', 'updated_by'])
    );
  });

  it('rifiuta type non valido', () => {
    const db = createDb(':memory:');
    expect(() =>
      db.prepare(`INSERT INTO content_blocks (tag, type, value) VALUES ('x.y', 'video', '')`).run()
    ).toThrow();
  });

  it('users ha colonna role con default admin', () => {
    const db = createDb(':memory:');
    db.prepare(`INSERT INTO users (username, password_hash) VALUES ('a', 'h')`).run();
    const row = db.prepare(`SELECT role FROM users WHERE username = 'a'`).get() as { role: string };
    expect(row.role).toBe('admin');
  });

  it('migra un DB esistente senza colonna role', () => {
    // simula DB vecchio: createDb due volte sullo stesso path in-memory non è possibile,
    // quindi si verifica che la migrazione sia idempotente (doppia esecuzione non lancia)
    const db = createDb(':memory:');
    expect(() => createDb(':memory:')).not.toThrow();
    expect(db.prepare(`PRAGMA table_info(users)`).all().length).toBeGreaterThanOrEqual(4);
  });
});
