jest.mock('nodemailer', () => ({ createTransport: jest.fn() }), {
  virtual: true,
});
import { WhatsAppBotEngine } from './whatsapp-bot.engine';

describe('Hybrid chatbot and Flow routing', () => {
  let bot: WhatsAppBotEngine,
    db: any,
    sessions: any,
    flows: any,
    orders: any,
    session: any;
  beforeEach(() => {
    session = {
      id: 's1',
      businessId: 'b1',
      customerId: 'c1',
      currentStep: 'WELCOME',
      sessionDataJson: '{}',
    };
    db = {
      business: {
        findMany: jest.fn().mockResolvedValue([]),
        findUnique: jest.fn().mockResolvedValue({ name: 'Quatrohaus' }),
      },
      customer: { findFirst: jest.fn().mockResolvedValue({ id: 'c1' }) },
    };
    sessions = {
      getOrCreateSession: jest.fn(async () => session),
      clearSession: jest.fn(),
      updateStep: jest.fn(),
      updateSessionData: jest.fn(),
    };
    flows = {
      needsConsent: jest.fn().mockResolvedValue(false),
      launch: jest.fn().mockResolvedValue({ text: 'Flow button' }),
      completion: jest.fn(),
      hostedWalletCheckout: jest
        .fn()
        .mockResolvedValue('https://payments.example/order'),
    };
    orders = {
      createOrderFromCart: jest.fn().mockResolvedValue({
        orderId: 'o1',
        orderNumber: 'ORDER1',
        currency: 'USD',
        totalAmount: 10,
      }),
    };
    bot = new WhatsAppBotEngine(
      db,
      sessions,
      {} as any,
      {} as any,
      orders,
      {} as any,
      {} as any,
      flows,
      {} as any,
    );
  });
  it('gates first-time users with consent before welcome or shopping', async () => {
    flows.needsConsent.mockResolvedValue(true);
    expect(await bot.processMessage('b1', '263771234567', 'hi')).toEqual({
      text: 'Flow button',
    });
    expect(flows.launch).toHaveBeenCalledWith(
      'b1',
      'c1',
      '263771234567',
      'consent',
    );
  });
  it('returns the existing welcome menu after verified consent', async () => {
    flows.completion.mockResolvedValue({ kind: 'consent' });
    const result = await bot.processMessage(
      'b1',
      '263771234567',
      'consent_flow:' + 'a'.repeat(64),
    );
    expect(result.text).toContain('Quatrohaus');
    expect(
      result.payload?.buttons?.some((button) => button.title === 'Shop'),
    ).toBe(true);
    expect(sessions.clearSession).toHaveBeenCalledWith('s1');
  });
  it('keeps Shop in chat and opens Search in a Flow', async () => {
    const shop = jest
      .spyOn(bot as any, 'renderShopCategories')
      .mockResolvedValue({ text: 'Chat categories' });
    expect(await bot.processMessage('b1', '263771234567', '1')).toEqual({
      text: 'Chat categories',
    });
    expect(shop).toHaveBeenCalled();
    expect(flows.launch).not.toHaveBeenCalled();
    await bot.processMessage('b1', '263771234567', '2');
    expect(flows.launch).toHaveBeenCalledWith(
      'b1',
      'c1',
      '263771234567',
      'search',
    );
  });
  it('hands the verified search result to existing product handling', async () => {
    flows.completion.mockResolvedValue({
      kind: 'search',
      productId: 'p1',
      variantId: null,
    });
    const details = jest
      .spyOn(bot as any, 'handleBrowseProductsStep')
      .mockResolvedValue({ text: 'Existing product detail' });
    expect(
      await bot.processMessage(
        'b1',
        '263771234567',
        'search_flow:' + 'b'.repeat(64),
      ),
    ).toEqual({ text: 'Existing product detail' });
    expect(details.mock.calls[0][2]).toMatchObject({ lastProductList: ['p1'] });
  });
  it('offers all three payment choices after existing order creation', async () => {
    session.currentStep = 'CHECKOUT_CONFIRM';
    const result = await bot.processMessage('b1', '263771234567', '1');
    expect(orders.createOrderFromCart).toHaveBeenCalled();
    expect(result.payload?.options?.map((option) => option.id)).toEqual([
      'card',
      'ecocash',
      'innbucks',
    ]);
    expect(sessions.updateStep).toHaveBeenCalledWith('s1', 'CHECKOUT_PAYMENT');
  });
  it('uses existing EcoCash collection and hosted PesePay for InnBucks', async () => {
    session.currentStep = 'CHECKOUT_PAYMENT';
    session.sessionDataJson = JSON.stringify({ pendingOrderId: 'o1' });
    await bot.processMessage('b1', '263771234567', 'ecocash');
    expect(sessions.updateStep).toHaveBeenCalledWith('s1', 'CHECKOUT_ECOCASH');
    const result = await bot.processMessage('b1', '263771234567', 'innbucks');
    expect(result.payload?.url).toBe('https://payments.example/order');
    expect(flows.hostedWalletCheckout).toHaveBeenCalledWith(
      'b1',
      '263771234567',
      'o1',
    );
  });
});
