'use strict';

const STATES = {
  NONE: 'NONE',
  REGISTER_SENT: 'REGISTER_SENT',
  AWAIT_REGISTER: 'AWAIT_REGISTER',
  LOGIN_SENT: 'LOGIN_SENT',
  AWAIT_LOGIN: 'AWAIT_LOGIN',
  DONE: 'DONE',
};

class AuthStateMachine {
  constructor(phrases, authTimeoutMs = 2500) {
    this.state = STATES.NONE;
    this.phrases = {
      register_success: phrases?.register_success || ['successfully registered'],
      already_registered: phrases?.already_registered || ['already registered', 'already logged'],
      login_success: phrases?.login_success || ['you have been logged', 'welcome back', 'successfully logged'],
    };
    this.authTimeoutMs = authTimeoutMs;
  }

  _matchesAny(haystack, needles) {
    if (!haystack) return false;
    const lower = haystack.toLowerCase();
    for (const n of needles) {
      if (lower.includes(n.toLowerCase())) return true;
    }
    return false;
  }

  /** Returns: 'register_sent' | 'login_sent' | 'auth_done' | null */
  consume({ text, translate }) {
    if (this.state === STATES.DONE) return null;

    if (translate) {
      if (translate === 'commands.register.success' && this.state === STATES.AWAIT_REGISTER) {
        this.state = STATES.DONE;
        return 'auth_done';
      }
      if (translate === 'commands.login.success' && this.state === STATES.AWAIT_LOGIN) {
        this.state = STATES.DONE;
        return 'auth_done';
      }
      if (translate === 'commands.login.alreadylogged' && (this.state === STATES.NONE || this.state === STATES.REGISTER_SENT)) {
        return 'login_sent';
      }
    }

    if (this._matchesAny(text, this.phrases.register_success) && this.state === STATES.AWAIT_REGISTER) {
      this.state = STATES.DONE;
      return 'auth_done';
    }
    if (this._matchesAny(text, this.phrases.already_registered) && (this.state === STATES.NONE || this.state === STATES.REGISTER_SENT)) {
      return 'login_sent';
    }
    if (this._matchesAny(text, this.phrases.login_success) && this.state === STATES.AWAIT_LOGIN) {
      this.state = STATES.DONE;
      return 'auth_done';
    }
    return null;
  }

  markRegisterSent() {
    if (this.state === STATES.NONE) this.state = STATES.REGISTER_SENT;
  }

  markAwaitRegister() {
    if (this.state === STATES.REGISTER_SENT) this.state = STATES.AWAIT_REGISTER;
  }

  markLoginSent() {
    if (this.state === STATES.NONE || this.state === STATES.REGISTER_SENT) this.state = STATES.LOGIN_SENT;
  }

  markAwaitLogin() {
    if (this.state === STATES.LOGIN_SENT) this.state = STATES.AWAIT_LOGIN;
  }

  isDone() {
    return this.state === STATES.DONE;
  }
}

module.exports = { AuthStateMachine, STATES };
