import { describe, it, expect } from 'bun:test';
import Database from 'bun:sqlite';
import { initializeDatabase } from '../../../src/db';

describe('Migración v9 - allowed_groups', () => {
  it('crea la tabla allowed_groups', () => {
    const memdb = new Database(':memory:');
    expect(() => initializeDatabase(memdb)).not.toThrow();

    const row = memdb
      .query(`SELECT name FROM sqlite_master WHERE type='table' AND name='allowed_groups'`)
      .get() as any;

    expect(row?.name).toBe('allowed_groups');
  });

  it('enforce CHECK de status', () => {
    const memdb = new Database(':memory:');
    initializeDatabase(memdb);

    // En bun:sqlite, exec() puede no lanzar en constraint violation. Validamos no persistencia.
    memdb.exec(`
      INSERT INTO allowed_groups (group_id, status, discovered_at, updated_at)
      VALUES ('123@g.us', 'invalid-status', strftime('%Y-%m-%d %H:%M:%f','now'), strftime('%Y-%m-%d %H:%M:%f','now'));
    `);

    const invalidCount = memdb
      .query(`SELECT COUNT(*) AS c FROM allowed_groups WHERE group_id = '123@g.us'`)
      .get() as any;
    expect(Number(invalidCount?.c || 0)).toBe(0);

    // Inserción válida debe persistir
    memdb.exec(`
      INSERT INTO allowed_groups (group_id, status, discovered_at, updated_at)
      VALUES ('ok@g.us', 'allowed', strftime('%Y-%m-%d %H:%M:%f','now'), strftime('%Y-%m-%d %H:%M:%f','now'));
    `);
    const validCount = memdb
      .query(`SELECT COUNT(*) AS c FROM allowed_groups WHERE group_id = 'ok@g.us'`)
      .get() as any;
    expect(Number(validCount?.c || 0)).toBe(1);
  });
});
