import { describe, it, expect, beforeEach, afterEach } from 'bun:test';
import { ResponseQueue } from '../../../src/services/response-queue';

describe('ResponseQueue - payload de reacción', () => {
  const OLD_FETCH = globalThis.fetch;

  beforeEach(() => {
    process.env.EVOLUTION_API_URL = 'http://evolution.local';
    process.env.EVOLUTION_API_INSTANCE = 'instance-1';
  });

  afterEach(() => {
    globalThis.fetch = OLD_FETCH;
    delete process.env.EVOLUTION_API_URL;
    delete process.env.EVOLUTION_API_INSTANCE;
  });

  it('incluye participant y fromMe cuando están presentes', async () => {
    const calls: any[] = [];
    globalThis.fetch = (async (url: any, init?: any) => {
      calls.push({ url, init });
      return {
        ok: true,
        status: 200,
        text: async () => ''
      } as any;
    }) as any;

    const item = {
      id: 1,
      recipient: '12345-67890@g.us',
      message: '',
      metadata: JSON.stringify({
        kind: 'reaction',
        emoji: '✅',
        chatId: '12345-67890@g.us',
        messageId: 'MSG-123',
        fromMe: true,
        participant: '34600123456@s.whatsapp.net'
      }),
      attempts: 0
    };

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

    expect(calls.length).toBe(1);
    const { url, init } = calls[0];
    expect(String(url)).toBe('http://evolution.local/message/sendReaction/instance-1');
    const payload = JSON.parse(String(init.body || '{}'));
    expect(payload).toBeTruthy();
    expect(payload.reaction).toBe('✅');
    expect(payload.key).toEqual({
      remoteJid: '12345-67890@g.us',
      fromMe: true,
      id: 'MSG-123',
      participant: '34600123456@s.whatsapp.net'
    });
  });

  it('omite participant y usa fromMe=false por defecto cuando no se proveen', async () => {
    const calls: any[] = [];
    globalThis.fetch = (async (url: any, init?: any) => {
      calls.push({ url, init });
      return {
        ok: true,
        status: 200,
        text: async () => ''
      } as any;
    }) as any;

    const item = {
      id: 2,
      recipient: '12345-67890@g.us',
      message: '',
      metadata: JSON.stringify({
        kind: 'reaction',
        emoji: '✅',
        chatId: '12345-67890@g.us',
        messageId: 'MSG-456'
      }),
      attempts: 0
    };

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

    const { url, init } = calls[0];
    expect(String(url)).toBe('http://evolution.local/message/sendReaction/instance-1');
    const payload = JSON.parse(String(init.body || '{}'));
    expect(payload.reaction).toBe('✅');
    expect(payload.key.remoteJid).toBe('12345-67890@g.us');
    expect(payload.key.id).toBe('MSG-456');
    expect(payload.key.fromMe).toBe(false);
    expect('participant' in payload.key).toBe(false);
  });
});
