import axios from 'axios';
import { BadRequestException, ServiceUnavailableException } from '@nestjs/common';
import { WhatsAppEmbeddedSignupService } from './whatsapp-embedded-signup.service';

jest.mock('axios');

describe('WhatsAppEmbeddedSignupService', () => {
  const env = { ...process.env };
  let businessService: { getDecryptedCredentials: jest.Mock; connectIntegration: jest.Mock };
  let service: WhatsAppEmbeddedSignupService;

  beforeEach(() => {
    jest.resetAllMocks();
    process.env = {
      ...env,
      META_APP_ID: '111',
      META_APP_SECRET: 'secret',
      META_EMBEDDED_SIGNUP_CONFIG_ID: '222',
      META_GRAPH_VERSION: 'v24.0',
    };
    businessService = {
      getDecryptedCredentials: jest.fn().mockResolvedValue({
        phoneNumberId: '55555',
        accessToken: 'old',
        shoppingFlowEnabled: true,
        shoppingFlowId: 'flow-1',
      }),
      connectIntegration: jest.fn().mockResolvedValue({ id: 'integ-1' }),
    };
    service = new WhatsAppEmbeddedSignupService(businessService as any);
    (axios.get as jest.Mock).mockImplementation((url: string) => {
      if (url.includes('oauth/access_token')) {
        return Promise.resolve({ data: { access_token: 'new-token' } });
      }
      if (url.includes('/phone_numbers')) {
        return Promise.resolve({
          data: { data: [{ id: '12345', display_phone_number: '+263 77 000 0000', verified_name: 'Shop' }] },
        });
      }
      return Promise.reject(new Error('unexpected ' + url));
    });
    (axios.post as jest.Mock).mockResolvedValue({ data: { success: true } });
  });

  afterAll(() => {
    process.env = env;
  });

  it('reports disabled config when env is missing', () => {
    delete process.env.META_EMBEDDED_SIGNUP_CONFIG_ID;
    expect(service.getPublicConfig().enabled).toBe(false);
    return expect(
      service.complete('biz', { code: 'c', wabaId: '99999', phoneNumberId: '12345' }),
    ).rejects.toBeInstanceOf(ServiceUnavailableException);
  });

  it('exchanges the code, saves the integration, subscribes and registers', async () => {
    const res = await service.complete('biz', { code: 'abc', wabaId: '99999', phoneNumberId: '12345', metaBusinessId: '777' });

    expect((axios.get as jest.Mock).mock.calls[0][1].params).toEqual({ client_id: '111', client_secret: 'secret', code: 'abc' });
    const saved = businessService.connectIntegration.mock.calls[0][1];
    expect(saved.integrationType).toBe('whatsapp');
    expect(saved.credentials).toMatchObject({
      phoneNumberId: '12345',
      accessToken: 'new-token',
      wabaId: '99999',
      metaBusinessId: '777',
      connectionMethod: 'embedded_signup',
      shoppingFlowEnabled: true,
      shoppingFlowId: 'flow-1',
    });
    expect(saved.credentials.registrationPinSecret).toMatch(/^\d{6}$/);

    const postUrls = (axios.post as jest.Mock).mock.calls.map((c) => c[0]);
    expect(postUrls).toEqual([
      'https://graph.facebook.com/v24.0/99999/subscribed_apps',
      'https://graph.facebook.com/v24.0/12345/register',
    ]);
    expect(res.success).toBe(true);
    expect(res.warnings).toEqual([]);
  });

  it('does not register coexistence numbers', async () => {
    await service.complete('biz', { code: 'abc', wabaId: '99999', phoneNumberId: '12345', coexistence: true });
    const postUrls = (axios.post as jest.Mock).mock.calls.map((c) => c[0]);
    expect(postUrls).toEqual(['https://graph.facebook.com/v24.0/99999/subscribed_apps']);
  });

  it('rejects a phone number that is not in the WABA', async () => {
    await expect(
      service.complete('biz', { code: 'abc', wabaId: '99999', phoneNumberId: '00000' }),
    ).rejects.toBeInstanceOf(BadRequestException);
    expect(businessService.connectIntegration).not.toHaveBeenCalled();
  });

  it('returns warnings instead of failing when registration fails', async () => {
    (axios.post as jest.Mock)
      .mockResolvedValueOnce({ data: { success: true } })
      .mockRejectedValueOnce({ response: { data: { error: { message: 'PIN mismatch' } } } });
    const res = await service.complete('biz', { code: 'abc', wabaId: '99999', phoneNumberId: '12345' });
    expect(res.success).toBe(true);
    expect(res.warnings[0]).toContain('PIN mismatch');
  });
});
