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

describe('CommandService - A4 JIT DM al asignador', () => {
  let memdb: Database;

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

  beforeEach(() => {
    process.env.NODE_ENV = 'test';
    process.env.METRICS_ENABLED = 'true';
    process.env.ONBOARDING_ENABLE_IN_TEST = 'true';
    process.env.CHATBOT_PHONE_NUMBER = '555111222';
    Metrics.reset();

    memdb.exec(`
      DELETE FROM task_assignments;
      DELETE FROM tasks;
      DELETE FROM users;
    `);
  });

  it('envía un único DM JIT al asignador con la lista y enlace wa.me cuando hay tokens no resolubles', async () => {
    const res = await CommandService.handle({
      sender: '111',
      groupId: '', // DM
      message: 't n Mixta @34600123456 @lid-opaque',
      mentions: [],
    });

    // Debe existir al menos el ACK y el JIT
    expect(res.length).toBeGreaterThan(0);

    const toSender = res.filter(r => r.recipient === '111');
    expect(toSender.length).toBeGreaterThan(0);

    const jit = toSender.find(r => r.message.includes('activar'));
    expect(jit).toBeTruthy();
    expect(jit!.message).toContain('lid-opaque');
    expect(jit!.message).toContain('https://wa.me/555111222');

    const prom = Metrics.render('prom');
    expect(prom).toContain('onboarding_prompts_sent_total');
    expect(prom).toContain('source="jit_assignee_failure"');
  });

  it('no envía JIT si falta CHATBOT_PHONE_NUMBER y contabiliza skipped:missing_bot_number', async () => {
    process.env.CHATBOT_PHONE_NUMBER = '';

    const res = await CommandService.handle({
      sender: '222',
      groupId: '',
      message: 't n Solo opaco @alias-xyz',
      mentions: [],
    });

    const anyJit = res.find(r => r.recipient === '222' && r.message.includes('activar'));
    expect(anyJit).toBeUndefined();

    const prom = Metrics.render('prom');
    expect(prom).toContain('onboarding_prompts_skipped_total');
    expect(prom).toContain('reason="missing_bot_number"');
  });
});
