module Twitch
  class RolesController < Twitch::BaseController
    before_action :set_user

    def edit
    end

    def update
      begin
        Twitch::Roles.update(
          params[:user_id],
          admin: params[:twitch_user][:admin] == '1',
          subadmin: params[:twitch_user][:subadmin] == '1',
          global_mod: params[:twitch_user][:global_mod] == '1'
        )
        audit = History::Audit.new(
          action: History::AUDIT_ACTION_UPDATE_ROLE,
          user_type: History::AUDIT_LDAP_USER,
          user_id: current_user.ldap_login,
          resource_type: History::AUDIT_TWITCH_USER,
          resource_id: params[:user_id],
          description: 'Elevated user role',
          changes: [
            History::ChangeSet.new(
              attribute: 'authorized_domain',
              new_value: @user.email.split('@').last.to_s
            )
          ]
        )
        History::AddAudit.add(audit)
        flash[:success] = 'Successfully updated user roles.'
      rescue UpdateRoles::InvalidEmailError
        flash[:error] = "Elevated roles must use an email with one of these domains: #{ACCEPTED_EMAIL_DOMAINS.map {|domain| "@#{domain}"}.to_sentence(two_words_connector: ' or ', last_word_connector: ', or ')}"
      rescue UpdateRoles::InvalidAdminEmailError
        flash[:error] = "Admins must use an email with one of these domains: #{ACCEPTED_ADMIN_EMAIL_DOMAINS.map {|domain| "@#{domain}"}.to_sentence(two_words_connector: ' or ', last_word_connector: ', or ')}"
      rescue UpdateRoles::InvalidSubAdminEmailError
        domains = (ACCEPTED_ADMIN_EMAIL_DOMAINS + ACCEPTED_SUB_ADMIN_EMAIL_DOMAINS)
        flash[:error] = "Sub-Admins must use an email with one of these domains: #{domains.map {|domain| "@#{domain}"}.to_sentence(two_words_connector: ' or ', last_word_connector: ', or ')}"
      rescue UpdateRoles::InvalidGlobalModEmailError
        domains = (ACCEPTED_ADMIN_EMAIL_DOMAINS + ACCEPTED_SUB_ADMIN_EMAIL_DOMAINS + ACCEPTED_EXTERNAL_EMAIL_DOMAINS)
        flash[:error] = "Mods must use an email with one of these domains: #{domains.map {|domain| "@#{domain}"}.to_sentence(two_words_connector: ' or ', last_word_connector: ', or ')}"
      rescue UpdateRoles::UnverifiedEmailError
        flash[:error] = 'User must have a verified email'
      rescue UpdateRoles::TwoFactorRequiredError
        flash[:error] = 'User must have two-factor authentication enabled'
      end

      redirect_to twitch_user_path(id: params[:user_id])
    end

    protected

    def set_user
      @user = User.find params[:user_id]
      authorize @user, :grant_admin_roles?
    end
  end
end
