import { describe, it, expect, beforeAll, beforeEach } from 'bun:test';
import { Database } from 'bun:sqlite';
import { initializeDatabase } from '../../src/db';
import { WebhookServer } from '../../src/server';
import { ResponseQueue } from '../../src/services/response-queue';
import { setDb } from '../../src/db/locator';

describe('WebhookServer - DM "activar" (A4)', () => {
  let memdb: Database;

  beforeAll(() => {
    memdb = new Database(':memory:');
    initializeDatabase(memdb);
    (WebhookServer as any).dbInstance = memdb;
    setDb(memdb);
  });

  beforeEach(() => {
    process.env.NODE_ENV = 'test';
    memdb.exec('DELETE FROM response_queue');
    memdb.exec('DELETE FROM users');
  });

  function rowCount(): number {
    const r = memdb.query("SELECT COUNT(*) AS c FROM response_queue").get() as any;
    return Number(r?.c || 0);
  }

  it('al recibir "activar" por DM, asegura usuario y encola confirmación', async () => {
    const data = {
      key: { remoteJid: '7001@s.whatsapp.net', fromMe: false },
      message: { conversation: 'activar' }
    };
    await WebhookServer.handleMessageUpsert(data);

    expect(rowCount()).toBe(1);
    const row = memdb.query("SELECT recipient, message FROM response_queue ORDER BY id").get() as any;
    expect(row.recipient).toBe('7001');
    expect(String(row.message).toLowerCase()).toContain('listo');
  });

  it('es idempotente: si envía "activar" de nuevo, se vuelve a encolar', async () => {
    const data = {
      key: { remoteJid: '8002@s.whatsapp.net', fromMe: false },
      message: { conversation: 'activar' }
    };
    await WebhookServer.handleMessageUpsert(data);
    await WebhookServer.handleMessageUpsert(data);

    expect(rowCount()).toBe(2);
  });
});
