import { SyncQueueService } from './sync-queue.service';

describe('Scheduled product polling', () => {
  const prisma = {
    business: { findMany: jest.fn() },
    syncLog: { findFirst: jest.fn() },
  };
  let service: SyncQueueService;

  beforeEach(() => {
    jest.clearAllMocks();
    service = new SyncQueueService(prisma as any, {} as any, {} as any);
    prisma.business.findMany.mockResolvedValue([
      { id: 'shop-1', integrations: [{ integrationType: 'woocommerce' }] },
    ]);
  });

  it('polls connected shops when no product import is running', async () => {
    prisma.syncLog.findFirst.mockResolvedValue(null);
    const trigger = jest
      .spyOn(service, 'triggerSync')
      .mockResolvedValue('log-1');
    await service.handleAutoScheduledSync();
    expect(trigger).toHaveBeenCalledWith('shop-1', 'products');
  });

  it('skips a shop while its previous product import is running', async () => {
    prisma.syncLog.findFirst.mockResolvedValue({ id: 'running-1' });
    const trigger = jest
      .spyOn(service, 'triggerSync')
      .mockResolvedValue('log-2');
    await service.handleAutoScheduledSync();
    expect(trigger).not.toHaveBeenCalled();
    expect(prisma.syncLog.findFirst).toHaveBeenCalledWith(
      expect.objectContaining({
        where: expect.objectContaining({
          businessId: 'shop-1',
          syncType: 'products',
          status: 'RUNNING',
        }),
      }),
    );
  });
});

describe('Native catalog review tracking', () => {
  it('does not reupload whitespace-only changes or count outdated items as approved', async () => {
    const products = [
      {
        id: 'local-1',
        externalProductId: '100',
        sku: null,
        name: 'Airpods',
        description: '\n\nShop description',
        price: 1,
        currency: 'USD',
        imageUrl: 'https://shop.example.com/image.jpg',
        status: 'ACTIVE',
        stockStatus: 'instock',
        variants: [],
      },
      {
        id: 'local-2',
        externalProductId: '101',
        sku: null,
        name: 'Speaker',
        description: 'Speaker description',
        price: 2,
        currency: 'USD',
        imageUrl: 'https://shop.example.com/speaker.jpg',
        status: 'ACTIVE',
        stockStatus: 'instock',
        variants: [],
      },
    ];
    const metaProducts = products.map((product, index) => ({
      ...product,
      sku: product.externalProductId,
      description: product.description.trim(),
      whatsappReviewStatus: index === 0 ? 'APPROVED' : 'OUTDATED',
    }));
    const connector = {
      fetchProducts: jest.fn().mockResolvedValue(metaProducts),
      upsertProducts: jest.fn(),
      batchUpdateVisibility: jest.fn(),
    };
    const prisma = {
      businessIntegration: {
        findFirst: jest.fn().mockResolvedValue({ id: 'integration' }),
      },
      product: { findMany: jest.fn().mockResolvedValue(products) },
      productVariant: { findMany: jest.fn().mockResolvedValue([]) },
    };
    const business = {
      getDecryptedCredentials: jest
        .fn()
        .mockResolvedValue({ catalogId: 'catalog', accessToken: 'test' }),
      updateLastConnected: jest.fn(),
    };
    const service = new SyncQueueService(
      prisma as any,
      { getConnector: () => connector } as any,
      business as any,
    );
    const result = await service.syncMetaCatalog('shop');
    expect(connector.upsertProducts).not.toHaveBeenCalled();
    expect(connector.batchUpdateVisibility).not.toHaveBeenCalled();
    expect(result).toEqual(
      expect.objectContaining({
        total: 2,
        nativeApproved: 1,
        nativeAwaitingReview: 1,
      }),
    );
  });
});

describe('Native catalog sync failures', () => {
  it('fails the sync log when live catalog credentials are missing', async () => {
    const prisma = {
      businessIntegration: {
        findFirst: jest
          .fn()
          .mockResolvedValue({ id: 'integration', integrationType: 'meta' }),
      },
      syncLog: { update: jest.fn() },
    };
    const business = {
      getDecryptedCredentials: jest.fn().mockResolvedValue(null),
    };
    const service = new SyncQueueService(
      prisma as any,
      {} as any,
      business as any,
    );
    await expect(service.syncMetaCatalog('shop', 'log')).rejects.toThrow(
      'live access token',
    );
    expect(business.getDecryptedCredentials).toHaveBeenCalledWith(
      'shop',
      'meta',
    );
    expect(prisma.syncLog.update).toHaveBeenCalledWith(
      expect.objectContaining({
        data: expect.objectContaining({ status: 'FAILED' }),
      }),
    );
  });

  it('reconciles newly uploaded products before completing the sync', async () => {
    const product = {
      id: 'local',
      externalProductId: '100',
      name: 'Speaker',
      price: 2,
      currency: 'USD',
      imageUrl: 'https://shop.example.com/image.jpg',
      status: 'ACTIVE',
      stockStatus: 'instock',
      variants: [],
    };
    const connector = {
      fetchProducts: jest
        .fn()
        .mockResolvedValueOnce([])
        .mockResolvedValue([
          { ...product, sku: '100', whatsappReviewStatus: 'APPROVED' },
        ]),
      upsertProducts: jest.fn(),
      batchUpdateVisibility: jest.fn(),
    };
    const prisma = {
      businessIntegration: {
        findFirst: jest
          .fn()
          .mockResolvedValue({ id: 'integration', integrationType: 'meta' }),
      },
      product: { findMany: jest.fn().mockResolvedValue([product]) },
      productVariant: { findMany: jest.fn().mockResolvedValue([]) },
    };
    const business = {
      getDecryptedCredentials: jest.fn().mockResolvedValue({
        metaCatalogId: 'catalog',
        metaAccessToken: 'token',
      }),
      updateLastConnected: jest.fn(),
    };
    const service = new SyncQueueService(
      prisma as any,
      { getConnector: () => connector } as any,
      business as any,
    );
    await expect(service.syncMetaCatalog('shop')).resolves.toEqual(
      expect.objectContaining({ total: 1, nativeApproved: 1 }),
    );
    expect(connector.upsertProducts).toHaveBeenCalledWith([
      expect.objectContaining({ retailerId: '100' }),
    ]);
    expect(connector.fetchProducts).toHaveBeenCalledTimes(2);
  });
});
