import { NotFoundException } from '@nestjs/common';
import { UltramsgSendController, numericUltramsgSendId } from './ultramsg-send.controller';
import type { MessageService } from '../message/message.service';

describe('UltramsgSendController quote fallback', () => {
  it('retries without quote when quotedMessageId is not found (list always sends msgId)', async () => {
    const sendText = jest
      .fn()
      .mockRejectedValueOnce(new NotFoundException('Message false_g@g.us_SID not found'))
      .mockResolvedValueOnce({ messageId: 'true_g@g.us_NEWID' });

    const controller = new UltramsgSendController({ sendText } as unknown as MessageService);
    const out = await controller.sendChat('sess-1', {
      token: 'k',
      to: '120363410816945817@g.us',
      body: 'ok',
      msgId: 'false_120363410816945817@g.us_ACB092F8F1EC8864A2619AD155EBE545_184589742010525@lid',
    });

    expect(typeof out.id).toBe('number');
    expect(out.id).toBeGreaterThan(0);
    expect(out.id).toBe(numericUltramsgSendId('true_g@g.us_NEWID'));
    expect(sendText).toHaveBeenCalledTimes(2);
    expect(sendText.mock.calls[0][1].quotedMessageId).toBe(
      'false_120363410816945817@g.us_ACB092F8F1EC8864A2619AD155EBE545',
    );
    expect(sendText.mock.calls[1][1].quotedMessageId).toBeUndefined();
  });

  it('returns a numeric id so PHP `$sendid > 0` passes (avoids fallback re-send)', async () => {
    const sendText = jest.fn().mockResolvedValue({ messageId: 'true_120363@g.us_3EB0ABC_out' });
    const controller = new UltramsgSendController({ sendText } as unknown as MessageService);
    const out = await controller.sendChat('sess-1', {
      token: 'k',
      to: '120363410816945817@g.us',
      body: 'ok',
    });
    expect(out.id).toBeGreaterThan(0);
    expect(Number.isInteger(out.id)).toBe(true);
  });

  it('does not swallow non-404 send errors', async () => {
    const sendText = jest.fn().mockRejectedValueOnce(new Error('engine down'));
    const controller = new UltramsgSendController({ sendText } as unknown as MessageService);
    await expect(
      controller.sendChat('sess-1', {
        token: 'k',
        to: '918956456710',
        body: 'ok',
        msgId: 'false_918956456710@c.us_ABCDEF1234567890AA',
      }),
    ).rejects.toThrow('engine down');
    expect(sendText).toHaveBeenCalledTimes(1);
  });
});
