class Admin::InvitationsController < Admin::BaseController
  def index
    @pending_invitations = User.where.not(invitation_token: nil)
                                .where(invitation_accepted_at: nil)
                                .order(invitation_sent_at: :desc)
    @accepted_invitations = User.where.not(invitation_accepted_at: nil)
                                 .order(invitation_accepted_at: :desc)
                                 .limit(20)
  end

  def new
    @invitation = User.new
  end

  def create
    @invitation = User.new(invitation_params)
    @invitation.invite_by(current_user)
    @invitation.password = SecureRandom.urlsafe_base64(16)

    if @invitation.save
      # Send invitation email
      InvitationMailer.invite(@invitation).deliver_later

      redirect_to admin_invitations_path, notice: "Invitation sent to #{@invitation.email}"
    else
      render :new, status: :unprocessable_entity
    end
  end

  def resend
    @invitation = User.find(params[:id])

    if @invitation.invitation_accepted_at.present?
      redirect_to admin_invitations_path, alert: "Cannot resend an accepted invitation."
      return
    end

    @invitation.invite_by!(current_user)

    InvitationMailer.invite(@invitation).deliver_later

    redirect_to admin_invitations_path, notice: "Invitation resent to #{@invitation.email}"
  end

  def destroy
    @invitation = User.find(params[:id])

    if @invitation.invitation_accepted_at.present?
      redirect_to admin_invitations_path, alert: "Cannot cancel an accepted invitation."
      return
    end

    @invitation.destroy
    redirect_to admin_invitations_path, notice: "Invitation cancelled."
  end

  private

  def invitation_params
    permitted = params.require(:user).permit(:email, :name, :primary_language)

    if params[:user][:role].present? && User.roles.key?(params[:user][:role])
      permitted[:role] = params[:user][:role]
    end

    permitted
  end
end
