import { describe, it, expect, vi, Mocked, beforeEach } from 'vitest';
import { SessionService } from './SessionService';
import { AuthApiClient } from '@/lib/api/auth/AuthApiClient';
import { SessionViewModel } from '@/lib/view-models/SessionViewModel';

describe('SessionService', () => {
  let mockApiClient: Mocked<AuthApiClient>;
  let service: SessionService;

  beforeEach(() => {
    mockApiClient = {
      getSession: vi.fn(),
    } as Mocked<AuthApiClient>;

    service = new SessionService(mockApiClient);
  });

  describe('getSession', () => {
    it('should call apiClient.getSession and return SessionViewModel when session exists', async () => {
      const mockResponse = {
        token: 'jwt-token',
        user: {
          userId: 'user-123',
          email: 'test@example.com',
          displayName: 'Test User',
        },
      };

      mockApiClient.getSession.mockResolvedValue(mockResponse);

      const result = await service.getSession();

      expect(mockApiClient.getSession).toHaveBeenCalled();
      expect(result.isOk()).toBe(true);
      const vm = result.unwrap();
      expect(vm).toBeInstanceOf(SessionViewModel);
      expect(vm?.userId).toBe('user-123');
      expect(vm?.email).toBe('test@example.com');
      expect(vm?.displayName).toBe('Test User');
      expect(vm?.isAuthenticated).toBe(true);
    });

    it('should return null when apiClient.getSession returns null', async () => {
      mockApiClient.getSession.mockResolvedValue(null);

      const result = await service.getSession();

      expect(mockApiClient.getSession).toHaveBeenCalled();
      expect(result.isOk()).toBe(true);
      expect(result.unwrap()).toBeNull();
    });

    it('should throw error when apiClient.getSession fails', async () => {
      const error = new Error('Get session failed');
      mockApiClient.getSession.mockRejectedValue(error);

      const result = await service.getSession();
      expect(result.isErr()).toBe(true);
      expect(result.getError().message).toBe('Get session failed');
    });
  });
});