import axios from 'axios';
import { MetaCatalogConnector } from './meta-catalog.connector';

jest.mock('axios');

describe('Native Meta catalog writes', () => {
  const client = { post: jest.fn(), get: jest.fn() };
  let connector: MetaCatalogConnector;
  const product = {
    externalId: '100',
    sku: 'SKU-100',
    name: 'Airpods',
    description: 'Shop description',
    imageUrl: 'https://shop.example.com/airpods.jpg',
    price: 0.01,
    currency: 'USD',
    stockStatus: 'instock' as const,
  };
  beforeEach(() => {
    jest.clearAllMocks();
    (axios.create as jest.Mock).mockReturnValue(client);
    client.post.mockResolvedValue({ data: { handles: ['batch-1'] } });
    client.get.mockResolvedValue({
      data: {
        data: [{ status: 'finished', errors: [], errors_total_count: 0 }],
      },
    });
    connector = new MetaCatalogConnector({
      catalogId: 'catalog-1',
      accessToken: 'test-token',
    });
  });

  it('sends feed fields and updates only the stable product ID', async () => {
    await connector.updateProduct('100', product);
    const payload = client.post.mock.calls[0][1];
    expect(payload.requests).toHaveLength(1);
    expect(payload.requests[0].data).toEqual(
      expect.objectContaining({
        id: '100',
        title: 'Airpods',
        image_link: product.imageUrl,
        price: '0.01 USD',
      }),
    );
    expect(payload.requests[0].data).not.toHaveProperty('name');
    expect(payload.requests[0].data).not.toHaveProperty('image_url');
  });

  it('surfaces asynchronous Meta validation errors', async () => {
    client.get.mockResolvedValue({
      data: {
        data: [
          {
            status: 'finished',
            errors_total_count: 1,
            errors: ['Invalid image'],
          },
        ],
      },
    });
    await expect(connector.updateProduct('100', product)).rejects.toThrow(
      'Invalid image',
    );
  });

  it('does not upsert incomplete visibility-only items', async () => {
    await connector.batchUpdateVisibility([
      { retailerId: '100', visibility: 'published', availability: 'in stock' },
    ]);
    expect(client.post.mock.calls[0][1].allow_upsert).toBe(false);
  });

  it('rejects missing images before writing any items', async () => {
    await expect(
      connector.updateProduct('100', { ...product, imageUrl: undefined }),
    ).rejects.toThrow('public image');
    expect(client.post).not.toHaveBeenCalled();
  });
  it('reads formatted Meta prices without losing cent values', async () => {
    client.get.mockResolvedValue({
      data: {
        data: [
          {
            id: 'node',
            retailer_id: '100',
            name: 'Airpods',
            price: '$0.01',
            currency: 'USD',
          },
          {
            id: 'node2',
            retailer_id: '101',
            name: 'Painting',
            price: '$1,200.00',
            currency: 'USD',
          },
        ],
      },
    });
    const products = await connector.fetchProducts();
    expect(products.map((p) => p.price)).toEqual([0.01, 1200]);
  });

  it('keeps WhatsApp review status separate from published visibility', async () => {
    client.get.mockResolvedValue({
      data: {
        data: [
          {
            id: 'node',
            name: 'Speaker',
            visibility: 'published',
            price: '$1.00',
            capability_to_review_status: [
              { key: 'WHATSAPP', value: 'OUTDATED' },
            ],
            image_fetch_status: 'FETCHED',
          },
        ],
      },
    });
    const [product] = await connector.fetchProducts();
    expect(product.status).toBe('ACTIVE');
    expect(product.whatsappReviewStatus).toBe('OUTDATED');
    expect(product.imageFetchStatus).toBe('FETCHED');
  });
});
