import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test'; import { Database } from 'bun:sqlite'; import { initializeDatabase } from '../../../src/db'; import { ResponseQueue } from '../../../src/services/response-queue'; let testDb: Database; let envBackup: NodeJS.ProcessEnv; describe('ResponseQueue (persistent add)', () => { beforeAll(() => { envBackup = { ...process.env }; testDb = new Database(':memory:'); initializeDatabase(testDb); // Inyectar DB de pruebas (ResponseQueue as any).dbInstance = testDb; }); afterAll(() => { process.env = envBackup; testDb.close(); }); beforeEach(() => { // Limpiar tabla entre tests testDb.exec('DELETE FROM response_queue'); // Valor por defecto del número del bot (se puede cambiar en tests) process.env.CHATBOT_PHONE_NUMBER = '1234567890'; }); test('should persist queued responses to database', async () => { const before = testDb.query("SELECT COUNT(*) as count FROM response_queue").get() as any; expect(before.count).toBe(0); await ResponseQueue.add([ { recipient: '111', message: 'hola 1' }, { recipient: '222', message: 'hola 2' }, ]); const after = testDb.query("SELECT COUNT(*) as count FROM response_queue").get() as any; expect(after.count).toBe(2); const rows = testDb.query("SELECT recipient, message, status FROM response_queue ORDER BY id").all() as any[]; expect(rows[0].recipient).toBe('111'); expect(rows[0].message).toBe('hola 1'); expect(rows[0].status).toBe('queued'); expect(rows[1].recipient).toBe('222'); expect(rows[1].message).toBe('hola 2'); expect(rows[1].status).toBe('queued'); }); test('should skip messages addressed to the bot number', async () => { process.env.CHATBOT_PHONE_NUMBER = '555111222'; await ResponseQueue.add([ { recipient: '555111222', message: 'no debe encolarse' }, { recipient: '333', message: 'debe encolarse' }, ]); const count = testDb.query("SELECT COUNT(*) as count FROM response_queue").get() as any; expect(count.count).toBe(1); const row = testDb.query("SELECT recipient, message FROM response_queue").get() as any; expect(row.recipient).toBe('333'); expect(row.message).toBe('debe encolarse'); }); test('should ignore entries without recipient or message', async () => { await ResponseQueue.add([ // inválidos: { recipient: '', message: 'sin destinatario' } as any, { recipient: '444', message: '' } as any, // válido: { recipient: '444', message: 'ok' }, ]); const rows = testDb.query("SELECT recipient, message FROM response_queue ORDER BY id").all() as any[]; expect(rows.length).toBe(1); expect(rows[0].recipient).toBe('444'); expect(rows[0].message).toBe('ok'); }); test('should throw if database error occurs (e.g., missing table)', async () => { // Provocar error: eliminar tabla testDb.exec('DROP TABLE response_queue'); await expect(ResponseQueue.add([{ recipient: '999', message: 'x' }])) .rejects .toBeTruthy(); // Restaurar esquema para no afectar otros tests initializeDatabase(testDb); }); });