import { Cookies } from 'react-cookie';
import { decodeToken, isValid, refreshAuth } from 'beta/utils/auth';
import { action, computed, extendObservable, makeObservable, observable } from 'mobx';

export interface IAccount {
  ssn: string;
  subscriptionId: string;
  customerId: string;
}

export default class Authentication {
  constructor({ authentication = {} }, account: IAccount, c: string | object | null) {
    this.accountInput = account;
    this.cookies = new Cookies(c);

    makeObservable(this, {
      isLoggingOut: observable,
      isRefreshingAuth: observable,
      isComingFromBeta: observable,
      accountInput: observable,
      isTokenValid: computed,
      isStaff: computed,
      setAccountInput: action,
      refresh: action,
      logout: action,
    });

    extendObservable(this, authentication);
  }

  cookies;

  isLoggingOut = false;

  isRefreshingAuth = false;

  isComingFromBeta = false;

  accountInput: IAccount;

  get token(): string {
    return this.cookies.get('token');
  }

  get isTokenValid() {
    return this.token && isValid(this.token);
  }

  get isStaff() {
    return decodeToken(this.token)?.is_staff === 'true';
  }

  get username() {
    return decodeToken(this.token)?.name;
  }

  get email() {
    return decodeToken(this.token)?.email;
  }

  get loggedInUserSsn() {
    return decodeToken(this.token)?.ssn;
  }

  get customerId() {
    return decodeToken(this.token)?.customer_id;
  }

  setAccountInput(
    ssn: string = this.accountInput?.ssn ?? '',
    subscriptionId: string = this.accountInput?.subscriptionId ?? '',
    customerId: string = this.accountInput?.customerId ?? '',
  ) {
    this.accountInput = { ssn, subscriptionId, customerId };
  }

  refresh = () => {
    this.isRefreshingAuth = true;

    refreshAuth(this.token);
  };

  logout = () => {
    this.isLoggingOut = true;
    this.cookies.remove('token', { path: '/' });
  };
}
