module Public
  class InvitationsController < WebBaseController
    def show
      @token = params[:token]
      @invitation = TeamInvitation.pending.find_by(token_digest: Digest::SHA256.hexdigest(@token.to_s))
      unless @invitation
        redirect_to public_pricing_path, alert: "Invito non valido o scaduto"
      end
    end

    def accept
      invitation = TeamInvitation.pending.find_by(token_digest: Digest::SHA256.hexdigest(params[:token].to_s))
      return redirect_to public_pricing_path, alert: "Invito non valido" unless invitation

      if logged_in?
        if current_user.email.downcase != invitation.email.downcase
          redirect_to public_pricing_path, alert: "Questo invito è per #{invitation.email}"
          return
        end
        invitation.accept!(current_user)
        redirect_to public_team_details_path(invitation.team), notice: "Sei entrato nella squadra!"
      else
        session[:pending_invite_token] = params[:token]
        redirect_to public_signup_path, notice: "Registrati con #{invitation.email} per accettare l'invito"
      end
    end
  end
end
