import { describe, it, expect, vi, beforeEach } from 'vitest';
import axios, { AxiosError } from 'axios';
import { verifyEmail } from './emailVerificationService';
import { apiClient } from '@/services/api/client';

// Mock apiClient
vi.mock('@/services/api/client', () => ({
  apiClient: {
    get: vi.fn(),
  },
}));

describe('emailVerificationService', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  describe('verifyEmail', () => {
    it('should call API GET /auth/verify-email?token=... with correct token', async () => {
      const token = 'test-token-123';
      const mockResponse = {
        data: {
          message: 'Email verified successfully',
          user_id: 1,
        },
      };

      vi.mocked(apiClient.get).mockResolvedValue(mockResponse);

      const result = await verifyEmail(token);

      expect(apiClient.get).toHaveBeenCalledWith(
        `/auth/verify-email?token=${token}`,
      );
      expect(result).toEqual(mockResponse.data);
    });

    it('should throw ApiError with error message from response', async () => {
      const token = 'invalid-token';
      const mockError = {
        response: {
          status: 400,
          data: {
            error: 'Invalid token',
          },
        },
      } as AxiosError;

      vi.mocked(apiClient.get).mockRejectedValue(mockError);

      await expect(verifyEmail(token)).rejects.toMatchObject({
        message: 'Invalid token',
        code: '400',
      });
    });

    it('should throw ApiError with network error message on network failure', async () => {
      const token = 'test-token';
      const mockError = {
        request: {},
      } as AxiosError;

      vi.mocked(apiClient.get).mockRejectedValue(mockError);

      await expect(verifyEmail(token)).rejects.toMatchObject({
        message: 'Network error: Unable to connect to server',
        code: 'NETWORK_ERROR',
      });
    });

    it('should throw ApiError with unknown error message on unexpected error', async () => {
      const token = 'test-token';
      const mockError = new Error('Unexpected error');

      vi.mocked(apiClient.get).mockRejectedValue(mockError);

      await expect(verifyEmail(token)).rejects.toMatchObject({
        message: 'Unexpected error',
        code: 'UNKNOWN_ERROR',
      });
    });
  });
});
