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.invitation_token = SecureRandom.urlsafe_base64(32)
    @invitation.invitation_sent_at = Time.current
    @invitation.invited_by = current_user
    @invitation.password = SecureRandom.urlsafe_base64(16)

    if @invitation.save
      # TODO: 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 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
    params.require(:user).permit(:email, :name, :role, :primary_language)
  end
end
