class AccountAuthsController < ApplicationController
  before_action :set_account_auth, only: [:update, :destroy]

  def index
    @account = Current.account
    if params[:account_id]
      @account = accounts.find(params[:account_id])
    end

    @members = account_auths.joins(:user).where(account: @account).order('role DESC, users.email ASC')
    @account_auth = account_auths.new(user: current_user, account: @account, role: :account_manager)
  end

  def create
    email = account_auths_create_params[:user_email]
    account_id = account_auths_create_params[:account_id]
    user = User.find_by(email: email)
    if user.nil?
      user = sign_up({ email: email, password: SecureRandom.alphanumeric })
      @account_auth = build_account_auth({ user: user, account_id: account_id, role: :account_manager })
      @account_auth.save!
      UserMailer.welcome(@account_auth.user, @account_auth.account).deliver_later
    else
      @account_auth = build_account_auth({ user: user, account_id: account_id, role: :account_manager })
      @account_auth.save!
      UserMailer.existing_account(@account_auth.user, @account_auth.account).deliver_later
    end
    redirect_to account_auths_path({ account_id: @account_auth.account_id }), notice: t(".notice")
  end

  def update
    AccountAuth.transaction do
      if @account_auth.update(account_auth_update_params)
        if @account_auth.account_manager?
          @account_auth.user.project_memberships.where(project: @account_auth.account.projects).destroy_all
        end
        flash.notice = t(".notice")
      else
        flash.alert = t(".alert")
      end
    end

    redirect_to account_auths_path
  end

  def destroy
    ActiveRecord::Base.transaction do
      ProjectMembership.where(user: @account_auth.user, project: @account_auth.account.projects).destroy_all
      @account_auth.destroy
    end
    redirect_to account_auths_path, alert: t(".alert")
  end

  private

  def build_account_auth(auth_params)
    @account_auth = authorize account_auths.build(auth_params)
  end

  def account_auths_create_params
    params.require(:account_auth).permit(:user_email, :account_id)
  end

  def account_auth_update_params
    params.require(:account_auth).permit(:role)
  end

  def account_auths
    policy_scope(AccountAuth)
  end

  def find_account_auth
    authorize account_auths.find(params[:id])
  end

  def accounts
    policy_scope(Account)
  end

  def set_account_auth
    @account_auth = find_account_auth
  end
end
