import { describe, expect, it, vi } from 'vitest';
import { 
  APIError, 
  ErrorType, 
  getErrorMessage, 
  handleNetworkError, 
  handleSupabaseError 
} from './error-handler';

describe('ErrorHandler Utility', () => {
  describe('APIError Class', () => {
    it('should create an instance with correct properties', () => {
      const error = new APIError('Test message', {
        status: 404,
        type: ErrorType.NotFound,
        code: 'PGRST116'
      });

      expect(error.message).toBe('Test message');
      expect(error.status).toBe(404);
      expect(error.type).toBe(ErrorType.NotFound);
      expect(error.code).toBe('PGRST116');
    });
  });

  describe('handleSupabaseError', () => {
    it('should map PGRST116 to NotFound', () => {
      const supabaseError = {
        code: 'PGRST116',
        message: 'JSON object requested, multiple (or no) rows returned',
        details: '',
        hint: ''
      };

      const result = handleSupabaseError(supabaseError);
      expect(result.type).toBe(ErrorType.NotFound);
      expect(result.status).toBe(404);
    });

    it('should map 42501 to Forbidden', () => {
      const supabaseError = {
        code: '42501',
        message: 'permission denied for table test',
        details: '',
        hint: ''
      };

      const result = handleSupabaseError(supabaseError);
      expect(result.type).toBe(ErrorType.Forbidden);
      expect(result.status).toBe(403);
    });
  });

  describe('handleNetworkError', () => {
    it('should handle axios style response errors', () => {
      const axiosError = {
        response: {
          status: 401,
          data: { message: 'Unauthorized' }
        }
      };

      const result = handleNetworkError(axiosError);
      expect(result.type).toBe(ErrorType.Unauthorized);
      expect(result.status).toBe(401);
    });

    it('should handle network connection errors', () => {
      const networkError = {
        request: {}
      };

      const result = handleNetworkError(networkError);
      expect(result.type).toBe(ErrorType.NetworkError);
    });
  });

  describe('getErrorMessage', () => {
    it('should return error message for APIError', () => {
      const error = new APIError('Özel hata mesajı', { type: ErrorType.ValidationError });
      expect(getErrorMessage(error)).toBe('Özel hata mesajı');
    });

    it('should return string directly if error is string', () => {
      expect(getErrorMessage('Düz metin hatası')).toBe('Düz metin hatası');
    });

    it('should return UnknownError message for unknown objects', () => {
      expect(getErrorMessage({})).toContain('Beklenmedik');
    });
  });
});
