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

describe('CommandService - JIT onboarding para menciones @lid y números demasiado largos', () => {
  let memdb: Database;

  beforeAll(() => {
    memdb = new Database(':memory:');
    initializeDatabase(memdb);
    setDb(memdb);
  });

  beforeEach(() => {
    process.env.NODE_ENV = 'test';
    process.env.ONBOARDING_ENABLE_IN_TEST = 'true';
    process.env.CHATBOT_PHONE_NUMBER = '34600000000';
    memdb.exec('DELETE FROM response_queue');
    memdb.exec('DELETE FROM users');
    memdb.exec('DELETE FROM tasks');
    memdb.exec('DELETE FROM task_assignments');
  });

  it('cuando la mención proviene de @lid, no se asigna y se devuelve un DM JIT al creador con wa.me', async () => {
    const res = await CommandService.handle({
      sender: '34611111111',
      groupId: '123@g.us',
      message: 't n Pedir cita @166348562894911',
      mentions: ['166348562894911@lid']
    });

    const toCreator = res.filter(r => r.recipient === '34611111111').map(r => r.message).join('\n');
    expect(toCreator).toMatch(/activar/i);
    expect(toCreator).toMatch(/https:\/\/wa\.me\/34600000000/);

    // No se devuelve ningún mensaje dirigido al "número" opaco
    const recipients = res.map(r => r.recipient);
    expect(recipients).not.toContain('166348562894911');
  });

  it('cuando el token @ lleva 15+ dígitos, no es plausible y devuelve DM JIT al creador', async () => {
    const res = await CommandService.handle({
      sender: '34622222222',
      groupId: '123@g.us',
      message: 't n Tarea prueba @123456789012345',
      mentions: []
    });

    const toCreator = res.filter(r => r.recipient === '34622222222').map(r => r.message).join('\n');
    expect(toCreator).toMatch(/activar/i);
    expect(toCreator).toMatch(/https:\/\/wa\.me\/34600000000/);

    const recipients = res.map(r => r.recipient);
    expect(recipients).not.toContain('123456789012345');
  });
});
