/**
 * Integrations Service Tests
 *
 * Tests the integrations API service including:
 * - Fetching all integrations
 * - Re-exported factory utilities
 */
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { getIntegrations, getIntegrationService, getIntegrationMetadata } from './integrations';

// Mock the apiRequest function
vi.mock('./api', () => ({
  apiRequest: vi.fn(),
}));

import { apiRequest } from './api';

describe('integrations service', () => {
  const mockIntegrations = [
    {
      slug: 'mailchimp',
      name: 'Mailchimp',
      description: 'Email marketing',
      connected: true,
      connection_count: 1,
    },
    {
      slug: 'slack',
      name: 'Slack',
      description: 'Team messaging',
      connected: false,
      connection_count: 0,
    },
  ];

  beforeEach(() => {
    vi.clearAllMocks();
  });

  // ==========================================================================
  // getIntegrations Tests
  // ==========================================================================

  describe('getIntegrations', () => {
    it('fetches all integrations from API', async () => {
      vi.mocked(apiRequest).mockResolvedValue(mockIntegrations);

      const result = await getIntegrations();

      expect(apiRequest).toHaveBeenCalledWith('/integrations');
      expect(result).toEqual(mockIntegrations);
    });

    it('returns empty array when no integrations', async () => {
      vi.mocked(apiRequest).mockResolvedValue([]);

      const result = await getIntegrations();

      expect(result).toEqual([]);
    });

    it('propagates API errors', async () => {
      const error = new Error('Network Error');
      vi.mocked(apiRequest).mockRejectedValue(error);

      await expect(getIntegrations()).rejects.toThrow('Network Error');
    });
  });

  // ==========================================================================
  // Re-exported Factory Utilities Tests
  // ==========================================================================

  describe('re-exported utilities', () => {
    it('exports getIntegrationService function', () => {
      expect(typeof getIntegrationService).toBe('function');
    });

    it('exports getIntegrationMetadata function', () => {
      expect(typeof getIntegrationMetadata).toBe('function');
    });
  });
});
