import { describe, it, beforeEach, afterEach, expect } from 'bun:test';
import { Database } from 'bun:sqlite';
import { initializeDatabase } from '../../../src/db';
import { ResponseQueue } from '../../../src/services/response-queue';
import { IdentityService } from '../../../src/services/identity';

const ORIGINAL_FETCH = globalThis.fetch;
const envBackup = { ...process.env };

describe('ResponseQueue - resolución de menciones con alias (@lid)', () => {
  let memdb: Database;
  let captured: { url?: string; payload?: any } = {};

  beforeEach(() => {
    process.env = {
      ...envBackup,
      EVOLUTION_API_URL: 'http://evolution.test',
      EVOLUTION_API_INSTANCE: 'instance-1',
      EVOLUTION_API_KEY: 'apikey'
    };

    memdb = new Database(':memory:');
    memdb.exec('PRAGMA foreign_keys = ON;');
    initializeDatabase(memdb);

    (IdentityService as any).dbInstance = memdb;
    (ResponseQueue as any).dbInstance = memdb;

    // Sembrar alias: userXYZ@lid -> 666777888
    IdentityService.upsertAlias('userXYZ@lid', '666777888@s.whatsapp.net', 'test');

    // Stub fetch para capturar el payload enviado
    globalThis.fetch = async (url: RequestInfo | URL, init?: RequestInit) => {
      captured.url = String(url);
      try {
        captured.payload = init?.body ? JSON.parse(String(init.body)) : null;
      } catch {
        captured.payload = null;
      }
      return new Response(JSON.stringify({ ok: true }), { status: 200, headers: { 'Content-Type': 'application/json' } });
    };
  });

  afterEach(() => {
    globalThis.fetch = ORIGINAL_FETCH;
    process.env = envBackup;
    memdb.close();
  });

  it('construye mentioned con números reales, deduplicados', async () => {
    const item = {
      id: 1,
      recipient: '123456789', // número normalizado
      message: 'hola @user',
      metadata: JSON.stringify({ mentioned: ['userXYZ@lid', '666777888@s.whatsapp.net'] }),
      attempts: 0
    };

    const res = await ResponseQueue.sendOne(item as any);
    expect(res.ok).toBe(true);

    expect(captured.url?.includes('/message/sendText/instance-1')).toBe(true);
    expect(captured.payload).toBeDefined();
    expect(captured.payload.number).toBe('123456789');
    expect(Array.isArray(captured.payload.mentioned)).toBe(true);

    // Debe contener solo una entrada, resuelta a número real @s.whatsapp.net y sin duplicados
    expect(captured.payload.mentioned.sort()).toEqual(['666777888@s.whatsapp.net']);
  });
});
