import { AuthenticationState } from './AuthenticationState';
import type { IValueObject } from '@core/shared/domain';

export interface BrowserAuthenticationStateProps {
  cookiesValid: boolean;
  pageAuthenticated: boolean;
}

export class BrowserAuthenticationState implements IValueObject<BrowserAuthenticationStateProps> {
  private readonly cookiesValid: boolean;
  private readonly pageAuthenticated: boolean;

  constructor(cookiesValid: boolean, pageAuthenticated: boolean) {
    this.cookiesValid = cookiesValid;
    this.pageAuthenticated = pageAuthenticated;
  }

  isFullyAuthenticated(): boolean {
    return this.cookiesValid && this.pageAuthenticated;
  }

  getAuthenticationState(): AuthenticationState {
    if (!this.cookiesValid) {
      return AuthenticationState.UNKNOWN;
    }

    if (!this.pageAuthenticated) {
      return AuthenticationState.EXPIRED;
    }

    return AuthenticationState.AUTHENTICATED;
  }

  requiresReauthentication(): boolean {
    return !this.isFullyAuthenticated();
  }

  getCookieValidity(): boolean {
    return this.cookiesValid;
  }

  getPageAuthenticationStatus(): boolean {
    return this.pageAuthenticated;
  }

  get props(): BrowserAuthenticationStateProps {
    return {
      cookiesValid: this.cookiesValid,
      pageAuthenticated: this.pageAuthenticated,
    };
  }

  equals(other: IValueObject<BrowserAuthenticationStateProps>): boolean {
    const a = this.props;
    const b = other.props;
    return a.cookiesValid === b.cookiesValid && a.pageAuthenticated === b.pageAuthenticated;
  }
}