class AccountsController < ApplicationController
  before_action :set_account, only: [:update]
  skip_before_action :require_login, only: [:new, :create]
  skip_after_action :verify_authorized, only: [:new, :create]

  def new
  end

  def create
    account = Account.create(account_params_for_create)

    if account.valid?
      user = sign_up(user_params)

      if user.valid?
        user.account_auths << AccountAuth.create(user: user, account: account, role: "account_manager")

        if sign_in(user)
          TrackAnalyticsJob.perform_later(user, user.primary_account, :track_guest_sign_up, user_agent: request.user_agent, user_ip: request.remote_ip)
          SubmitHubspotFormJob.perform_later(user.email, account.name, i_m_interested_in: user.interested_product_name)
          redirect_to signed_in_root_path
        else
          redirect_to new_session_path, alert: t(".notice")
        end
      else
        redirect_to new_account_path, alert: t(".error")
      end
    else
      redirect_to new_account_path, alert: t(".error")
    end
  end
  
  def update
    authorize @account

    @account.update(account_params_for_update)
  end

  private

  def set_account
    @account = Current.account
  end

  def account_params_for_create
    { name: params[:user][:account_name], plan_uid: :me_suite }
  end

  def account_params_for_update
    params.require(:account).permit(:logo)
  end

  def user_params
    params.require(:user).except(:account_name).permit(:email, :password, :first_name, :last_name, :interested_product_name)
  end
end
