import { describe, it, expect, beforeEach, vi } from 'vitest';
import { VerifyAuthenticatedPageUseCase } from 'apps/companion/main/automation/application/use-cases/VerifyAuthenticatedPageUseCase';
import { AuthenticationServicePort as IAuthenticationService } from 'apps/companion/main/automation/application/ports/AuthenticationServicePort';
import { Result } from '@core/shared/application/Result';
import { BrowserAuthenticationState } from 'apps/companion/main/automation/domain/value-objects/BrowserAuthenticationState';
import { AuthenticationState } from 'apps/companion/main/automation/domain/value-objects/AuthenticationState';

describe('VerifyAuthenticatedPageUseCase', () => {
  let useCase: VerifyAuthenticatedPageUseCase;
  let mockAuthService: {
    checkSession: ReturnType<typeof vi.fn>;
    verifyPageAuthentication: ReturnType<typeof vi.fn>;
    initiateLogin: ReturnType<typeof vi.fn>;
    clearSession: ReturnType<typeof vi.fn>;
    getState: ReturnType<typeof vi.fn>;
    validateServerSide: ReturnType<typeof vi.fn>;
    refreshSession: ReturnType<typeof vi.fn>;
    getSessionExpiry: ReturnType<typeof vi.fn>;
  };

  beforeEach(() => {
    mockAuthService = {
      checkSession: vi.fn(),
      verifyPageAuthentication: vi.fn(),
      initiateLogin: vi.fn(),
      clearSession: vi.fn(),
      getState: vi.fn(),
      validateServerSide: vi.fn(),
      refreshSession: vi.fn(),
      getSessionExpiry: vi.fn(),
    };
    useCase = new VerifyAuthenticatedPageUseCase(
      mockAuthService as unknown as IAuthenticationService
    );
  });

  it('should return fully authenticated browser state', async () => {
    const mockBrowserState = new BrowserAuthenticationState(true, true);
    mockAuthService.verifyPageAuthentication.mockResolvedValue(
      Result.ok(mockBrowserState)
    );

    const result = await useCase.execute();

    expect(result.isOk()).toBe(true);
    const browserState = result.unwrap();
    expect(browserState.isFullyAuthenticated()).toBe(true);
    expect(browserState.getAuthenticationState()).toBe(AuthenticationState.AUTHENTICATED);
  });

  it('should return unauthenticated state when page not authenticated', async () => {
    const mockBrowserState = new BrowserAuthenticationState(true, false);
    mockAuthService.verifyPageAuthentication.mockResolvedValue(
      Result.ok(mockBrowserState)
    );

    const result = await useCase.execute();

    expect(result.isOk()).toBe(true);
    const browserState = result.unwrap();
    expect(browserState.isFullyAuthenticated()).toBe(false);
    expect(browserState.getAuthenticationState()).toBe(AuthenticationState.EXPIRED);
  });

  it('should return requires reauth state when cookies invalid', async () => {
    const mockBrowserState = new BrowserAuthenticationState(false, false);
    mockAuthService.verifyPageAuthentication.mockResolvedValue(
      Result.ok(mockBrowserState)
    );

    const result = await useCase.execute();

    expect(result.isOk()).toBe(true);
    const browserState = result.unwrap();
    expect(browserState.requiresReauthentication()).toBe(true);
    expect(browserState.getAuthenticationState()).toBe(AuthenticationState.UNKNOWN);
  });

  it('should propagate errors from verifyPageAuthentication', async () => {
    const error = new Error('Verification failed');
    mockAuthService.verifyPageAuthentication.mockResolvedValue(
      Result.err(error)
    );

    const result = await useCase.execute();

    expect(result.isErr()).toBe(true);
    if (result.isErr()) {
      expect(result.error).toBeInstanceOf(Error);
      expect(result.error?.message).toBe('Verification failed');
    }
  });

  it('should handle unexpected errors', async () => {
    mockAuthService.verifyPageAuthentication.mockRejectedValue(
      new Error('Unexpected error')
    );

    const result = await useCase.execute();

    expect(result.isErr()).toBe(true);
    if (result.isErr()) {
      expect(result.error).toBeInstanceOf(Error);
      expect(result.error?.message).toBe('Page verification failed: Unexpected error');
    }
  });
});